You are on page 1of 142

Appendix A

Practices and Solutions






Oracle Spatial 11g: Essentials A - 2
Table of Contents

Practices for Lesson 1......................................................................................................... 3
Practice 1-1: Overview of Oracle Spatial Concepts ....................................................... 4
Practices for Lesson 2......................................................................................................... 6
Practice 2-1: Creating Spatial Layers ............................................................................. 7
Practices for Lesson 3....................................................................................................... 16
Practice 3-1: Defining Collection Geometries.............................................................. 17
Practices for Lesson 4....................................................................................................... 20
Practice 4-1: Associating Spatial Layers with Coordinate Systems ............................. 21
Practices for Lesson 5....................................................................................................... 24
Practice 5-1: Loading Spatial Data ............................................................................... 25
Practices for Lesson 6....................................................................................................... 33
Practice 6-1: Validating and Debugging Geometries ................................................... 34
Practices for Lesson 7....................................................................................................... 38
Practice 7-1: Using the Oracle Application Server MapViewer................................... 39
Practices for Lesson 8....................................................................................................... 46
Practice 8-1: Indexing Spatial Data .............................................................................. 47
Practices for Lesson 9....................................................................................................... 51
Practice 9-1: Querying Spatial Data ............................................................................. 52
Practices for Lesson 10..................................................................................................... 59
Practice 10-1: Using the SDO_WITHIN_DISTANCE, SDO_NN, and SDO_JOIN
Operators....................................................................................................................... 60
Practices for Lesson 11..................................................................................................... 63
Practice 11-1: Analyzing Geometries by Using Spatial Operators and Functions ....... 64
Practices for Lesson 12..................................................................................................... 70
Practice 12-1: Using Spatial Analysis, MBR, Utility, and Aggregate Functions......... 71
Practices for Lesson 13..................................................................................................... 75
Practice 13-1: Defining Maps by Using the Map Builder Tool.................................... 76
Practices for Lesson 14..................................................................................................... 92
Practice 14-1: Leveraging Oracle Maps: The Map Cache and JavaScript API............ 93
Practices for Lesson 15................................................................................................... 102
Practice 15-1: Creating a User-Defined Coordinate System...................................... 103
Practices for Lesson 16................................................................................................... 104
Practice 16-1: Implementing a Linear Referencing System....................................... 105
Practices for Lesson 17................................................................................................... 110
Practice 17-1: Managing Spatial Indexes ................................................................... 111
Practices for Lesson 18................................................................................................... 119
Practice 18-1: Geocoding Address Data..................................................................... 120
Practices for Lesson 19................................................................................................... 132
Practice 19-1: Using the Spatial Routing Engine ....................................................... 133



Oracle Spatial 11g: Essentials A - 3
Practices for Lesson 1
In this practice, you answer questions to recapitulate Oracle Spatial concepts and
terminologies discussed in the lesson.


Oracle Spatial 11g: Essentials A - 4
Practice 1-1: Overview of Oracle Spatial Concepts
1) State true or false for the following statements about the Points geometry:
i) A 2D point defines a location in X and Y coordinates.
ii) A point may be used to represent the location of a building or an automated
teller machine (ATM).
Answer:
a) i) True
b) ii) True
2) State true or false for the following statements about the Line Strings geometry:
i) Self-crossing line strings are invalid.
ii) When line strings close to form a ring, they have an area.
iii) The boundary of a line string is defined by its end points.
Answer:
a) i) False
b) ii) False
c) iii) True
3) State true or false for the following statements about the Polygons geometry:
i) Polygons have an area.
ii) Self-crossing polygons are valid and supported in Oracle Spatial
Answer:
a) i) True
b) ii) False
4) Define an optimized rectangle.
Answer: An optimized rectangle is a polygon represented by the lower-left point and the
upper-right point of the rectangle.
5) Answer whether the statement is true or false:
i) An outer ring polygon is defined in the counterclockwise direction. Answer:
True
ii) Inner rings must be followed by its outer ring. Answer: False
iii) A geometry must be composed of the same element types. Answer: False
iv) An Oracle tables column of the SDO_GEOMETRY type is defined as a spatial
layer. Answer: True
v) A spatial layer can contain different types of geometries. Answer: True
vi) Tolerance defines the precision of spatial data. Answer: True
Practice 1-1: Overview of Oracle Spatial Concepts (continued)
Oracle Spatial 11g: Essentials A - 5
6) Fill in the blank spaces:
i) A rectangle that minimally encloses a geometry is called a
_____________________(Answer: minimum bounding rectangle)
ii) An optimized circle is a polygon defined by_____________distinct points on
the circumference of the circle. (Answer: three)
iii) The primary filter uses the ________________ to compare geometry
approximations to get a superset of the result. (Answer: spatial index)
7) Match the following:

Term Definition
a) Geocoding a) Associates a measure value with each
2D or 3D point along a linear feature
b) Linear Referencing System b) Provides routing information such as
driving distances, or directions between
two locations
c) Routing c) Associates latitude and longitude
coordinates with postal addresses

Answer: The term and definition matched pairs are: (a, c), (b, a), (c, b).



Oracle Spatial 11g: Essentials A - 6
Practices for Lesson 2
In Part 1 of this practice, you create a table, geom_data, with a spatial column and
insert different types of geometries in the table.
In Part 2 of this practice, you create some more tables for storing spatial data. The data in
these tables will be loaded later in Practice 5-1. You also update the
USER_SDO_GEOM_METADATA view.


Oracle Spatial 11g: Essentials A - 7
Practice 2-1: Creating Spatial Layers
Part 1:
1) Start SQL*Plus and log in using student/student as the username/password.
Answer:
a) On your desktop, double-click the SQL*Plus icon.
b) Enter the following command:
conn student/student.


2) Describe the SDO_GEOMETRY data type and review its attributes and member
functions.
Answer:
a) At the SQL*Plus prompt, enter the following command:
DESCRIBE SDO_GEOMETRY
b) The output is shown in the following screenshots:
Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 8



3) Create a table, geom_data, with the following structure:
i) Object_id number PRIMARY KEY
ii) Name varchar2(30)
iii) Shape SDO_GEOMETRY
Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 9
Answer:
a) Enter the following code to create the geom_data table:
CREATE TABLE geom_data (
object_id number primary key,
name varchar2(30),
shape SDO_GEOMETRY);


4) Insert a two-dimensional point with the following coordinates and nonspatial attribute
values. Use the SDO_POINT field. Set SRID to NULL.
i) Object_id: 1
ii) Name: Point
iii) Coordinates: X=12, Y=14
Answer: To insert a point by using the SDO_POINT field, enter the following INSERT
statement:

INSERT INTO geom_data VALUES(
1, 'Point',
SDO_GEOMETRY( 2001, NULL,
SDO_POINT_TYPE(12, 14, NULL),
NULL,
NULL)
);










Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 10
5) Insert a line string composed of straight lines by using the following values:
i) Object_id: 2
ii) Name: Line String
iii) Coordinates: (10,25), (20,30), (25,25), (30,30)
iv) Set SRID to NULL.
Answer: To insert a line string, enter the following command:
INSERT INTO geom_data VALUES (
2,'Line String',
SDO_GEOMETRY (2002, NULL, NULL,
SDO_ELEM_INFO_ARRAY (1,2,1),
SDO_ORDINATE_ARRAY (10,25, 20,30, 25,25, 30,30))
);


6) Insert an optimized rectangle by using the following values:
i) Object_id: 3
ii) Name: Rectangle
iii) Coordinates: (1,1), (5,7)
iv) Set SRID to NULL.
Answer: To insert an optimized rectangle, enter the following command:
INSERT INTO geom_data VALUES(
3,'Rectangle',
SDO_GEOMETRY(2003, NULL, NULL,
SDO_ELEM_INFO_ARRAY(1,1003, 3),
SDO_ORDINATE_ARRAY(1,1, 5,7))
);





Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 11
7) Insert a polygon with a hole by using the following values:
i) Object_id: 4
ii) Name: Polygon with a hole
iii) Coordinates:
(1) Outer ring polygon: (2,4), (4,3), (10,3), (13,5), (13,9),
(11,13), (5,13), (2,11), (2,4)
(2) Inner ring polygon: (7,5), (7,10), (10,10), (10,5), (7,5)
Answer: To insert a polygon with a hole by using the given coordinates, enter the
following command:
INSERT INTO geom_data VALUES(
4,'Polygon with a hole',
SDO_GEOMETRY(2003, NULL,NULL,
SDO_ELEM_INFO_ARRAY(1,1003,1, 19,2003,1),
SDO_ORDINATE_ARRAY(2,4, 4,3, 10,3, 13,5, 13,9, 11,13,
5,13, 2,11, 2,4,7,5, 7,10, 10,10, 10,5, 7,5))
);




If you want an extra challenge, complete the following exercise:
8) Insert a compound polygon with the following values:
i) Object_id: 5
ii) Name: Compound Polygon
iii) Shape:
Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 12



Answer: To insert the compound polygon, enter the following INSERT statement:

INSERT INTO geom_data VALUES(
5, 'Compound Polygon',
SDO_GEOMETRY(2003, NULL, NULL,
SDO_ELEM_INFO_ARRAY(1,1005,2, 1,2,1, 5,2,2),
SDO_ORDINATE_ARRAY(6,10, 10,1, 14,10, 10,14, 6,10)
)
);



Part 2:
9) Create the following tables:
i) GEOD_CITIES
Column name Data type Description
LOCATION SDO_GEOMETRY City location
CITY VARCHAR2(42) City name
STATE_ABRV VARCHAR2(2) State code
POP90 NUMBER Population (1990)
RANK90 NUMBER Population ranking (1990)

ii) GEOD_INTERSTATES
Column name Data type Description
HIGHWAY VARCHAR2(35) Interstate name
GEOM SDO_GEOMETRY Interstate geometry
Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 13
Answer: To create the tables as described, enter and run the following code:
CREATE TABLE GEOD_CITIES(
LOCATION SDO_GEOMETRY,
CITY VARCHAR2(42),
STATE_ABRV VARCHAR2(2),
POP90 NUMBER,
RANK90 NUMBER);

CREATE TABLE GEOD_INTERSTATES(
HIGHWAY VARCHAR2(35),
GEOM SDO_GEOMETRY);



10) Describe the structure of the USER_SDO_GEOM_METADATA view.
Answer: To view the structure of the USER_SDO_GEOM_METADATA view, enter the
following command:
DESCRIBE USER_SDO_GEOM_METADATA









Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 14
11) Insert metadata for the following layers into the USER_SDO_GEOM_METADATA
view:
i) GEOM_DATA (SHAPE):
(1) Set SRID to NULL.
(2) Set the tolerance to 0.005.
(3) For SDO_DIM_ARRAY, set the x-axis in the range from 0 to 300 and
y-axis in the range from 0 to 300.
ii) GEOD_CITIES (LOCATION):
(1) Set SRID to 8307.
(2) Set the tolerance to 0.05.
(3) For SDO_DIM_ARRAY, set the Long axis in the range from 180.0 to
180.0 and the Lat axis in the range from 90.0 to 90.0.
iii) GEOD_INTERSTATES (GEOM):
(1) Set SRID to 8307.
(2) Set the tolerance to 0.05.
(3) For SDO_DIM_ARRAY, set the Long axis in the range from 180.0 to
180.0 and the Lat axis in the range from 90.0 to 90.0.
Note: Spatial data is loaded into the GEOD_CITIES and GEOD_INTERSTATES
tables in the lesson titled, Loading Spatial Data. Make sure you commit the
inserted rows.

Answer: To individually update the USER_SDO_GEOM_METADATA view with details
about each table, enter and run the following:
INSERT INTO user_sdo_geom_metadata(TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID) VALUES (
'GEOM_DATA',
'SHAPE',
SDO_DIM_ARRAY(
SDO_DIM_ELEMENT('X', 0, 300, 0.005),
SDO_DIM_ELEMENT('Y', 0, 300, 0.005)
),
NULL);

INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID) VALUES (
'GEOD_CITIES',
'LOCATION',
SDO_DIM_ARRAY(
SDO_DIM_ELEMENT('LONG', -180.0, 180.0, 0.05),
SDO_DIM_ELEMENT('LAT', -90.0, 90.0, 0.05)),
8307);
Practice 2-1: Creating Spatial Layers (continued)
Oracle Spatial 11g: Essentials A - 15

INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID) VALUES(
'GEOD_INTERSTATES',
'GEOM',
SDO_DIM_ARRAY(
SDO_DIM_ELEMENT('LONG', -180.0, 180.0, 0.05),
SDO_DIM_ELEMENT('LAT', -90.0, 90.0, 0.05)),
8307);
commit;














Oracle Spatial 11g: Essentials A - 16
Practices for Lesson 3
In this practice, you insert collection geometries in the geom_data table. You also use
some of the SDO_GEOMETRY member methods and constructors.

Prerequisite: To successfully perform this practice, you must have completed the
previous practice. If you did not perform the previous practice for lesson 2 completely,
start a new SQL* Plus window and run the
d:\labs\catchup_scripts\prac_02.sql file.


Oracle Spatial 11g: Essentials A - 17
Practice 3-1: Defining Collection Geometries
1) Insert an oriented point in the geom_data table by using the following values:
i) Object_id: 6
ii) Name: Oriented Point
iii) Coordinates: (12,14)
iv) Orientation vector values: (0.3, 0.2)
Answer: To insert an oriented point, enter the following INSERT statement:

INSERT INTO geom_data VALUES(
6, 'Oriented Point',
SDO_GEOMETRY(2001, NULL, NULL,
SDO_ELEM_INFO_ARRAY(1,1,1, 3,1,0),
SDO_ORDINATE_ARRAY(12,14, 0.3,0.2))
);


2) Insert a multiline geometry composed of two line strings. Use the following values:
i) Object_id: 7
ii) Name: Multiline
iii) Coordinates: (50,22, 60,22) (65,20, 65,25)
Answer: To insert a multiline, enter the following code:

INSERT INTO geom_data VALUES (
7,'Multiline',
SDO_GEOMETRY (2006, NULL, NULL,
SDO_ELEM_INFO_ARRAY (1,2,1, 5,2,1),
SDO_ORDINATE_ARRAY (50,22, 60,22, 65,20, 65,25))
);
Practice 3-1: Defining Collection Geometries (continued)
Oracle Spatial 11g: Essentials A - 18



3) Insert a multipolygon geometry composed of two rectangles touching at one point.
Use the following values:
i) Object_id: 8
ii) Name: Multipolygon-touching
iii) Coordinates: (50,115, 65,125, 65,125, 75,130)
Answer: To insert a multipolygon, enter the following code:

INSERT INTO geom_data VALUES (
8,'Multipolygon touching',
SDO_GEOMETRY (2007, NULL, NULL,
SDO_ELEM_INFO_ARRAY (1,1003,3, 5,1003,3),
SDO_ORDINATE_ARRAY (50,115, 65,125, 65,125, 75,130))
);


4) Write a query to get the dimension and the GTYPE of the geometry object with
Object_id as 4.
Answer: To get the dimension and GTYPE, enter the following code:

SELECT g.shape.Get_Dims(), g.shape.Get_Gtype()
FROM geom_data g
WHERE g.object_id = 4;
Practice 3-1: Defining Collection Geometries (continued)
Oracle Spatial 11g: Essentials A - 19


5) Write a query to get the Well-Known Text format of the geometry object with
Object_id as 5.
Note: In the SQL prompt, run set long 150 to see the full output.
Answer: To get the Well-Known Text format, enter the following code:

SELECT g.shape.Get_WKT()
FROM geom_data g
WHERE g.object_id = 5;



If you want extra challenge, complete the following exercise:
6) Insert a point geometry by using a Well-Known Text string constructor into the
geom_data table. Set object_id to 9 and Name to Point. The point coordinates
are (80, 40).
Answer: To insert a point by using the Well-Known Text string constructor, enter the
following code:

INSERT INTO geom_data VALUES (
9, 'Point',
SDO_GEOMETRY('POINT(80 40)')
);




Oracle Spatial 11g: Essentials A - 20
Practices for Lesson 4
In this practice, you run coordinate system transformation routines on geometries. The
routines transform the geometries into a new coordinate system.

Prerequisite: This practice does not use any of the database objects created in the
previous practices. So you can perform this practice even if you did not finish the
previous practices.


Oracle Spatial 11g: Essentials A - 21
Practice 4-1: Associating Spatial Layers with Coordinate
Systems
1) Describe the CS_SRS table.
Answer: Enter the following command:

DESCRIBE CS_SRS



2) Run the lab_04_02.sql script located in the D:\labs\labs folder. This script
creates the geom_shapes table and inserts two geometries with the SRID 8307.
Answer: Run the lab_04_02.sql script at the SQL prompt:

@d:\labs\labs\lab_04_02.sql


3) View the two inserted geometries. The spatial column in the table, geom_shapes,
is shape.
Answer: Run the following query:

SELECT shape FROM geom_shapes;
Practice 4-1: Associating Spatial Layers with Coordinate
Systems (continued)
Oracle Spatial 11g: Essentials A - 22


4) Insert a new row for geom_shapes(shape) in the
USER_SDO_GEOM_METADATA view.
i) Set the tolerance to 0.05.
ii) Set the Long axis range: 180 to 180.
iii) Set the Lat axis range: 90 to 90.
iv) Set SRID to 8307.
Answer: Insert the spatial layer details in the USER_SDO_GEOM_METADATA view:

INSERT INTO user_sdo_geom_metadata
(TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES(
'geom_shapes', 'shape',
SDO_DIM_ARRAY(
SDO_DIM_ELEMENT('Longitude', -180, 180, 0.05),
SDO_DIM_ELEMENT('Latitude', -90, 90, 0.05)
),
8307
);
COMMIT;
5) Transform the geometry with Object_id as 1 in the geom_shapes table to 32618
(WGS 84/UTM zone 18N).
Note: In this transformation, the original geometry is not actually transformed. The
transformed geometry is displayed as a result.
Answer: Enter the following query:
SELECT SDO_CS.TRANSFORM(g.shape, 0.05, 32618)
FROM geom_shapes g
WHERE g.object_id=1;
Practice 4-1: Associating Spatial Layers with Coordinate
Systems (continued)
Oracle Spatial 11g: Essentials A - 23


6) Transform the entire shape layer and put results in the table named
geom_shapes_CS_32618.
Note: This transformation procedure actually transforms the geometries into the new
coordinate system and stores the results in the new table,
geom_shapes_CS_32618. The new table is created by the procedure itself.
Answer: Run the following statement at the SQL prompt:

CALL SDO_CS.TRANSFORM_LAYER(
'geom_shapes','shape','geom_shapes_CS_32618',32618);

7) Describe the geom_shapes_CS_32618 table.
Answer: Run the following command:

DESCRIBE geom_shapes_CS_32618


8) Select all the geometries from the geom_shapes_CS_32618 table.
Answer: Run the following query:

SELECT geometry FROM geom_shapes_CS_32618;



Oracle Spatial 11g: Essentials A - 24
Practices for Lesson 5
In this practice, first, you load the GEOD_CITIES and GEOD_INTERSTATES tables by
using SQL*Loader. The respective .ctl and .dat files are located in the
D:\labs\data folder. Then you import spatial data from the Data Pump import files,
geod_counties.dmp and proj_data.dmp, located in the d:\labs\data
folder. Finally, you use the SampleShapefileToJGeomFeature utility to process
a STATES shapefile.
Prerequisite: To successfully perform this practice, you must have completed the
practice for the lesson titled Creating Spatial Layers.
If you did not perform any of the previous practices and you want to bring up your
schema to the desired state, start a new SQL* Plus window and run the SQL script,
d:\labs\catchup_scripts\prac_0203.sql.


Oracle Spatial 11g: Essentials A - 25
Practice 5-1: Loading Spatial Data

Loading spatial data by using SQL*Loader
1) The GEOD_CITIES and GEOD_INTERSTATES tables were created in a previous
exercise. You now perform the following tasks:
i) Load the GEOD_CITIES table by using the geod_cities.dat and
geod_cities.ctl files.
ii) Load the GEOD_INTERSTATES table by using the
geod_interstates.dat and geod_interstates.ctl files.
iii) The respective .dat and .ctl files are located in the D:\labs\data
folder. Invoke sqlldr to load data in the two tables.
Answer: To invoke SQL*Loader, open a command prompt window.
a) In the command prompt window, change to the D:\labs\data folder. Enter
the following command at the command prompt:
sqlldr student/student control=geod_cities.ctl
data=geod_cities.dat direct=true



Note: If you do not want to enter the command, you can run the
d:\labs\soln\sol_05_01_a.bat file to accomplish the same task.

b) Similarly, load the data in the geod_interstates table by using the
geod_interstates.ctl and geod_interstates.dat files.
sqlldr student/student control=geod_interstates.ctl data=
geod_interstates.dat direct=true
Practice 5-1: Loading Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 26



Note: If you do not want to enter the command, you can run the
d:\labs\soln\sol_05_01_b.bat file to accomplish the same task.

Loading spatial data by using Data Pump import
2) Import the GEOD_COUNTIES table from the geod_counties.dmp file. Use Data
Pump import. The geod_counties.dmp file is in the D:\labs\data folder.
Note: Before you can use the impdp command to import the geod_counties table,
log in using system/oracle as the username/password and then create a directory
object named student_dumpdir, using the CREATE DIRECTORY statement. The
system user must grant read and write privileges on the directory,
student_dumpdir, to the user student. You can create a log file named
geod_counties.log and save it in the D:\labs\data folder, just in case you
want to monitor errors if any.
Answer: Perform the following steps:
a) First, log in using system/oracle as the username/password. Create a
directory by entering the following SQL statement at the SQL prompt:
conn system/oracle
CREATE DIRECTORY student_dumpdir as 'D:\labs\data';
b) Grant read and write privileges to student.
grant read, write on directory student_dumpdir to student;


c) Open a command window and then use the impdp command to import the
geod_counties.dmp file.
impdp student/student dumpfile =
student_dumpdir:geod_counties.dmp
logfile = student_dumpdir:geod_counties.log
Practice 5-1: Loading Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 27



Note: If you do not want to enter the command, you can run the
d:\labs\soln\sol_05_02_c.bat file to import the geod_counties.dmp
file.

3) In SQL*Plus, connect again as the student user. Describe the GEOD_COUNTIES
table and also check the number of records in the table.
Answer: Run the following queries:

conn student/student
DESCRIBE geod_counties;
SELECT count(*) from geod_counties;


4) Insert metadata for the GEOD_COUNTIES(GEOM) layer into the
USER_SDO_GEOM_METADATA view. Commit the record.
i) Set the tolerance to 0.05.
ii) Set the SRID to 8307.
iii) Set the Long axis range to 180 to 180.
iv) Set the Lat axis range to 90 to 90.
Practice 5-1: Loading Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 28
Answer: Run the following INSERT statement:

INSERT INTO USER_SDO_GEOM_METADATA
(TABLE_NAME, COLUMN_NAME, DIMINFO, SRID)
VALUES
('GEOD_COUNTIES', 'GEOM',
SDO_DIM_ARRAY
(SDO_DIM_ELEMENT('X', -180.0, 180.0, 0.05),
SDO_DIM_ELEMENT('Y', -90.0, 90.0, 0.05)
),
8307);
commit;


5) Import the following tables from the proj_data.dmp file:
i) PROJ_CITIES
ii) PROJ_INTERSTATES
iii) PROJ_COUNTIES
iv) PROJ_STATES
Note: Locate the proj_data.dmp file in the D:\labs\data folder. Use the
same student_dumpdir directory for the import. Generate a
proj_data.log file.

Answer: Run the following command at the command prompt:

impdp student/student dumpfile = student_dumpdir:proj_data.dmp
logfile = student_dumpdir:proj_data.log
Practice 5-1: Loading Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 29



Note: If you do not want to enter the command, you can run the
d:\labs\soln\sol_05_05.bat file to import the proj_data.dmp file.

6) Insert metadata for the following layers:
i) PROJ_CITIES(LOCATION)
ii) PROJ_INTERSTATES(GEOM)
iii) PROJ_COUNTIES(GEOM)
iv) PROJ_STATES(GEOM)
Note: Use the following details for all the tables:
i) X, 11000000, 4000000, 0.05
ii) Y, 80000, 7000000, 0.05
iii) SRID: 32775
Answer: Run the following INSERT statements:

INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID)
VALUES ('PROJ_CITIES', 'LOCATION',
SDO_DIM_ARRAY
(SDO_DIM_ELEMENT('X', -11000000, 4000000, 0.05),
SDO_DIM_ELEMENT('Y', -80000, 7000000, 0.05)
),
32775);

INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID)
VALUES ('PROJ_COUNTIES', 'GEOM',
SDO_DIM_ARRAY
Practice 5-1: Loading Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 30
(SDO_DIM_ELEMENT('X', -11000000, 4000000, 0.05),
SDO_DIM_ELEMENT('Y', -80000, 7000000, 0.05)
),
32775);

INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID)
VALUES ('PROJ_INTERSTATES', 'GEOM',
SDO_DIM_ARRAY
(SDO_DIM_ELEMENT('X', -11000000, 4000000, 0.05),
SDO_DIM_ELEMENT('Y', -80000, 7000000, 0.05)
),
32775);

INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID)
VALUES ('PROJ_STATES', 'GEOM',
SDO_DIM_ARRAY
(SDO_DIM_ELEMENT('X', -11000000, 4000000, 0.05),
SDO_DIM_ELEMENT('Y', -80000, 7000000, 0.05)
),
32775);
COMMIT;


Using the Shapefile Converter Utility
7) Run the Java sample SampleShapefileToJGeomFeature utility on the
STATES shapefile provided. Perform the following:
i) Set the classpath to
.;%ORACLE_HOME%\jdbc\lib\ojdbc5.jar;%ORACLE_HOME%\md
\jlib\sdoutl.jar;%ORACLE_HOME%\md\jlib\sdoapi.jar.
Make sure that ORACLE_HOME is set before setting the classpath.
ii) Run the SampleShapefileToJGeomFeature Java-based tool.
Note: The SampleShapefileToJGeomFeature Java utility loads polygons
in the four-digit spatial SDO_GTYPE format, taking into account polygon rotation
and ring ordering.
iii) Locate the STATES files in the D:\labs\data\shapefile folder.
Answer: Perform the following step:
a) Open a command window. Change to the D:\labs\data\shapefile folder.
Set the classpath. If ORACLE_HOME and OC4J_HOME are not set, set them too as
follows:
cd d:\labs\data\shapefile
set ORACLE_HOME=d:\app\administrator\product\11.1.0\db_1
Practice 5-1: Loading Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 31
set
clpath=.;%ORACLE_HOME%\jdbc\lib\ojdbc5.jar;%ORACLE_HOME%\md\jl
ib\sdoutl.jar;%ORACLE_HOME%\md\jlib\sdoapi.jar

b) To run the Shapefile converter utility, run the following command at the
command prompt:
java -cp %clpath%
oracle.spatial.util.SampleShapefileToJGeomFeature -h localhost
-p 1521 -s orcl -u student -d student -t geod_states -f states
-r 8307 -g geom



Note: Alternatively, if you do not want to enter the whole path, the classpath, and the
Java command, run the sol_05_07.bat file. If your ORACLE_HOME is in anyway
different from what is mentioned in the preceding code box, edit the sol_05_07.bat
file before running.
8) Run the verify_labs.sql script to check whether all the data is loaded correctly
with the correct SDO_GTYPE, SRID, and number of rows. The
verify_labs.sql script is located in the D:\labs\labs folder.
Answer: Run the following script and check the output:
@d:\labs\labs\verify_labs.sql
Practice 5-1: Loading Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 32

The output must be as shown in the following screenshot:




Oracle Spatial 11g: Essentials A - 33
Practices for Lesson 6
In this practice, you insert invalid geometries and then use validation functions to validate
them. You also use debugging functions to correct geometries.

Prerequisite: To successfully complete this practice, you must have completed the
practices for the lessons titled Creating Spatial Layers and Defining Collection
Geometries. If you did not complete the practices, run
d:\labs\catchup_scripts\prac_0203.sql.

Prerequisite for the remaining practices:
For the remaining practices, it is recommended that your schema is fully loaded with the
desired tables. If you did not complete the practice for the lesson titled Loading Spatial
Data, it is important that you perform the following steps to bring your schema to the
state it should be for the remaining practices. Even if this practice is not dependent on
practice 5-1, it ensures that your practices run successfully for the remaining lessons. Run
the scripts in the following sequence [all the scripts (.sql and .bat files) are located in
the d:\labs\catchup_scripts folder]:
i) If you did not complete the practices for the lessons titled Creating Spatial
Layers and Defining Collection Geometries, open a new SQL*Plus
window and enter the following command:
@d:\labs\catchup_scripts\prac_0203.sql
ii) In Windows Explorer, double-click
load_geod_cities_interstates.bat to run the batch file.
iii) In SQL*Plus, enter the following command:
@d:\labs\catchup_scripts\create_directory.sql
iv) In Windows Explorer, double-click load_geod_proj_data.bat to run
it.
v) In SQL*Plus, enter the following command:
@d:\labs\catchup_scripts\update_metadata.sql
vi) In Windows Explorer, double-click the load_geod_states.bat file.


Oracle Spatial 11g: Essentials A - 34
Practice 6-1: Validating and Debugging Geometries
1) Before you use the validation and debugging functions, insert a few invalid
geometries in the geom_data table. Run the lab_06_01.sql script to insert
invalid geometries in the geom_data table. The lab_06_01.sql script is in the
D:\labs\labs folder.
Answer: At the SQL prompt, enter the following command:
@D:\labs\labs\lab_06_01.sql
2) Validate the geometry with Object_id as 10.
Answer: Run the following query:

SELECT SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT(g.shape, 0.05)
FROM geom_data g
WHERE g.object_id = 10;



Note: The error 13351 has the following description:
ORA-13351: Two or more rings of a complex polygon overlap.
Cause: The inner or outer rings of a complex polygon overlap.
Action: All rings of a complex polygon must be disjoint. Correct the geometric
definition of the object.
3) Create a val_results table with the following structure:
Column name Data type
sdo_rowid ROWID
result VARCHAR2(1000)

Answer: Run the following SQL statement:

CREATE TABLE val_results(
sdo_rowid ROWID,
result VARCHAR2(1000)
);







Practice 6-1: Validating and Debugging Geometries (continued)
Oracle Spatial 11g: Essentials A - 35
4) Validate the geom_data(shape)spatial layer and review the validation results.
Answer: Perform the following steps:
a) To validate the entire layer, run the following statement:
CALL
SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT('GEOM_DATA','SHAPE',
'VAL_RESULTS');
Note: The values in the procedure must be in uppercase.
b) View the records in the val_results table:
SELECT * FROM val_results;



Note: Out of the 13 rows processed, four rows have invalid geometries. The
VAL_RESULTS table contains the ROWID of the geometry and the associated error
number and its description in the RESULT column.
5) Write a query to return the vertices of the geometry object with Object_id as 13.
Answer: Run the following query:

SELECT t.X, t.Y
FROM geom_data g,
TABLE(SDO_UTIL.GETVERTICES(g.shape)) t
WHERE g.Object_id=13;
Practice 6-1: Validating and Debugging Geometries (continued)
Oracle Spatial 11g: Essentials A - 36


Note: Notice the redundant vertices.
6) Remove redundant vertices from the geometry object with Object_id as 13.
Answer: Run the following query:

SELECT sdo_util.rectify_geometry(g.shape, 0.5)
FROM geom_data g
where g.object_id=13;


7) Debug the geometry object with Object_id as 11. Use the RECTIFY_GEOMETRY
function. First, verify in the val_results table and find out what is wrong with
the geometry.
Answer: Perform the following steps:
a) Find out the ROWID of the geometry so that you can search for the corresponding
ROWID in the val_results table.
SELECT ROWID FROM geom_data WHERE object_id=11;


b) Search the result column for the same ROWID and find out the error number
associated with it.
SELECT result FROM val_results
WHERE SDO_ROWID='AAARF8AAEAAAAAOAAJ';
Practice 6-1: Validating and Debugging Geometries (continued)
Oracle Spatial 11g: Essentials A - 37
Note: This ROWID will be different for you, so do not copy it from here. If you are
running the solution script, sol_06_07_b.sql, replace your ROWID in the query.



Note: The error description is as follows:
ORA-13349: The polygon boundary crosses itself.
Cause: The boundary of a polygon intersects itself.
Action: Correct the geometric definition of the object.
c) Now, run the rectify_geometry function to debug the geometry.
SELECT sdo_util.rectify_geometry(g.shape,0.05)
FROM geom_data g
WHERE rowid='AABH8IAAGAAAAAOAAB';



Note: Replace the ROWID in your query with the ROWID of your geometry.
8) From the geometry object identified by Object_id as 8, extract the first element.
Answer: Run the following query:

SELECT sdo_util.extract(g.shape, 1,0)
FROM geom_data g
WHERE g.object_id=8;





Oracle Spatial 11g: Essentials A - 38
Practices for Lesson 7
In this practice, you install MapViewer. You also view data in MapViewer. For this
practice, access the zip file called mv10131_qs.zip located in the
D:\labs\software folder.

Prerequisite: To perform this practice completely, you must have completed the practice
for the lesson titled Loading Spatial Data successfully. If you did not, perform the steps
mentioned in the section Prerequisite for the remaining practices: in the practice for
lesson 6.



Oracle Spatial 11g: Essentials A - 39
Practice 7-1: Using the Oracle Application Server MapViewer
1) Extract the mv10131_qs.zip file under the root directory on D: drive.
Note: You can extract the mv10131_qs.zip file anywhere outside your
ORACLE_HOME.
Answer: Perform the following steps:
a) From Windows Explorer, double-click mv10131_qs.zip to start WinZip, and
extract it to the local disk (the root directory on the D: drive is D:\).
b) Click the Extract button. Enter D:\ in the Extract to field of the pop-up menu.
Click Extract. When you extract the file, it creates the
D:\mv10131_qs directory.
2) Initialize OC4J and deploy MapViewer. Edit the start.bat file in your
D:\mv10131_qs folder. Deploy MapViewer by running start.bat. Choose
welcome as the oc4jadmin password when prompted.
Answer: Perform the following steps to initialize OC4J and to deploy MapViewer:
a) Navigate to the D:\mv10131_qs directory.
b) Right-click start.bat and make the following edits:
i) On the first line, change C: to D:.
ii) On the second line, change C: to D:.
iii) Because the bin directory for Java JDK 1.5 is in your path environment
variable, on the third line, replace C:\Program
Files\Java\jdk1.5.0\bin\java with java.
c) Save the start.bat file. Exit the editor.
d) In Windows Explorer, double-click the start.bat file to run it. A read-only
console window is displayed. This is where MapViewer reports information and
error messages.
e) Choose welcome as the oc4jadmin password when prompted. You must
remember this password. In the console window, you should observe the
following message:
Practice 7-1: Using the Oracle Application Server MapViewer
(continued)
Oracle Spatial 11g: Essentials A - 40
INFO [oracle.lbs.mapserver.oms] *** Oracle MapViewer
started. ***


Note: Do not close this command window.
3) Create a dynamic data source. A data source defines the connection information to the
database for map requests. Define a data source with the Oracle Application Server
MapViewer Admin JSP.
Answer: Perform the following steps:
a) Open Internet Explorer. The Oracle Application Server MapViewer Admin JSP is
located at: http://localhost:8888/mapviewer.


Practice 7-1: Using the Oracle Application Server MapViewer
(continued)
Oracle Spatial 11g: Essentials A - 41
b) On the upper-right corner of the page, click Admin. To perform administrative
commands, such as adding a data source, enter oc4jadmin in the User Name
field and welcome in the Password field. Click Log In.

c) Under the Management tab, click Datasources under Manage MapViewer, as
shown in the following screenshot:

d) In the Create a dynamic data source section, update the fields with the
following values:
i) Name: student
ii) Host: localhost
Practice 7-1: Using the Oracle Application Server MapViewer
(continued)
Oracle Spatial 11g: Essentials A - 42
iii) Port: 1521
iv) Sid: orcl
v) User: student
vi) Password: student
vii) # Mappers: 3

e) Click Submit. The student data source should be listed under Existing data
sources.

4) View the data you loaded in the lesson titled Loading Spatial Data by using
MapViewer. Select the geometries from the geom_states and geom_counties
tables.
Practice 7-1: Using the Oracle Application Server MapViewer
(continued)
Oracle Spatial 11g: Essentials A - 43
Answer: Perform the following steps:
a) From the MapViewer page, click the Demos tab.
b) Click the JView demo.

c) When the Simple Spatial Query Visualizer page is displayed, in the top query
window (query 1:), enter:
SELECT geom FROM geod_counties
d) Set the line color to red and the fill to yellow. Enter COUNTY in the Label Column
field
e) In the second query window (query 2:), enter:
SELECT geom FROM geod_states

Note: Do not end the query with a semicolon.
f) Set the line color to black and leave the fill empty. Enter STATE in the Label
Column field
g) Click the Submit button.
Practice 7-1: Using the Oracle Application Server MapViewer
(continued)
Oracle Spatial 11g: Essentials A - 44


h) Zoom in to a location to see more detail.


Note: Similarly, you can try selecting the location column from geod_cities,
or the geom column from geod_interstates.
5) Configure the student data source. On the MapViewer Admin page, configure a
data source that automatically starts when MapViewer is started.
Answer: Perform the following steps:
a) Navigate to MapViewer home page. On the upper-right corner of the MapViewer
page, click Admin.
Practice 7-1: Using the Oracle Application Server MapViewer
(continued)
Oracle Spatial 11g: Essentials A - 45
b) Under the Management tab, select Configuration under Manage MapViewer.
c) At the bottom of the configuration file, search for the Predefined Data sources
section. Uncomment the example map_data_source element, and modify the
following values:
i) Name: student
ii) Host: localhost
iii) Port: 1521
iv) Sid: orcl
v) User: student
vi) Password: !student
vii) # Mappers: 3

d) Click Save & Restart. The student data source should be listed under Existing
data sources. Note that "!student" causes MapViewer to encrypt this
password after the first time MapViewer is started with this data source defined.
You can verify this by looking at the configuration file.


Oracle Spatial 11g: Essentials A - 46
Practices for Lesson 8
In this practice, you create nonspatial and spatial indexes on spatial layers.

Prerequisite: To perform this practice completely, you must have completed the practice
for the lesson titled Loading Spatial Data successfully. If you did not, perform the steps
mentioned in the section Prerequisite for the remaining practices in the practice for
lesson 6.


Oracle Spatial 11g: Essentials A - 47
Practice 8-1: Indexing Spatial Data
1) Create nonspatial indexes on the following columns. Make sure that all the indexes
are created on the indx_tblspc tablespace already created for you.
i) GEOD_CITIES(CITY)
ii) GEOD_STATES(STATE)
iii) GEOD_STATES(STATE_ABRV)
iv) GEOD_INTERSTATES(HIGHWAY)
v) GEOD_COUNTIES(STATE, COUNTY)
vi) GEOD_COUNTIES(STATE_ABRV, COUNTY)
Note: The following nonspatial indexes were created on the projected layers during
import:

i) PROJ_CITIES(CITY)
ii) PROJ_STATES(STATE)
iii) PROJ_STATES(STATE_ABRV)
iv) PROJ_INTERSTATES(HIGHWAY)
v) PROJ_COUNTIES(STATE, COUNTY)
vi) PROJ_COUNTIES(STATE_ABRV, COUNTY)
Answer: To create nonspatial indexes, run the following statements:
CREATE INDEX geod_cities_idx ON geod_cities(city) TABLESPACE
indx_tblspc;

CREATE INDEX geod_counties_idx ON geod_counties(state, county)
TABLESPACE indx_tblspc;

CREATE INDEX geod_counties_abrv_idx ON
geod_counties(state_abrv, county) TABLESPACE indx_tblspc;

CREATE INDEX geod_states_idx ON geod_states(state) TABLESPACE
indx_tblspc;

CREATE INDEX geod_states_abrv_idx ON geod_states(state_abrv)
TABLESPACE indx_tblspc;

CREATE INDEX geod_interstates_idx ON geod_interstates(highway)
TABLESPACE indx_tblspc;

Practice 8-1: Indexing Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 48
2) Create spatial (R-tree) indexes on the following layers. Again, set the tablespace
parameter to the indx_tblspc tablespace. Also, set the work tablespace parameter
to the work_indx_tblspc tablespace.
i) GEOD_CITIES(LOCATION)
ii) GEOD_INTERSTATES(GEOM)
iii) GEOD_COUNTIES(GEOM)
iv) GEOD_STATES(GEOM)
v) PROJ_CITIES(LOCATION)
vi) PROJ_STATES(GEOM)
vii) PROJ_INTERSTATES(GEOM)
viii) PROJ_COUNTIES(GEOM)

Answer: Run the following statements to create spatial indexes:

CREATE INDEX geod_cities_sidx on geod_cities (location)
INDEXTYPE IS mdsys.spatial_index
PARAMETERS ('layer_gtype=point, work_tablespace =
work_indx_tblspc, tablespace =indx_tblspc');


create index GEOD_INTERSTATES_SIDX on GEOD_INTERSTATES (GEOM)
indextype is mdsys.spatial_index
parameters ('layer_gtype=multiline, work_tablespace =
work_indx_tblspc, tablespace =indx_tblspc');

create index GEOD_COUNTIES_SIDX on GEOD_COUNTIES (GEOM)
indextype is mdsys.spatial_index
parameters ('layer_gtype=multipolygon, work_tablespace =
work_indx_tblspc, tablespace =indx_tblspc');

create index GEOD_STATES_SIDX on GEOD_STATES (GEOM)
indextype is mdsys.spatial_index
parameters ('layer_gtype=multipolygon , work_tablespace
= work_indx_tblspc, tablespace =indx_tblspc');

create index PROJ_CITIES_SIDX on PROJ_CITIES (LOCATION)
indextype is mdsys.spatial_index
parameters ('layer_gtype=point, work_tablespace =
work_indx_tblspc, tablespace =indx_tblspc');

create index PROJ_STATES_SIDX on PROJ_STATES (GEOM)
indextype is mdsys.spatial_index
parameters ('layer_gtype=multipolygon, work_tablespace =
work_indx_tblspc, tablespace =indx_tblspc');

Practice 8-1: Indexing Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 49
create index PROJ_INTERSTATES_SIDX on PROJ_INTERSTATES (GEOM)
indextype is mdsys.spatial_index
parameters ('layer_gtype=multiline, work_tablespace =
work_indx_tblspc, tablespace =indx_tblspc');

create index PROJ_COUNTIES_SIDX on PROJ_COUNTIES (GEOM)
indextype is mdsys.spatial_index
parameters ('layer_gtype=multipolygon, work_tablespace =
work_indx_tblspc, tablespace =indx_tblspc');
3) Describe USER_SDO_INDEX_METADATA.
Answer: Run the following command:

DESCRIBE USER_SDO_INDEX_METADATA

Note that this view does not have information such as the table name and the column
name on which the index was built.
4) Describe the USER_SDO_INDEX_INFO view. Write a query to select all the rows
from the USER_SDO_INDEX_INFO view. Appropriately set the line size to view the
results in a formatted manner.
DESCRIBE user_sdo_index_info
SELECT * FROM user_sdo_index_info;

Note: This view contains information about the table name and column name on
which the index was built.
5) Estimate the size of an R-tree index on a table that has 200,000 geometries,
DB_BLOCK_SIZE set to 16 KB (16384), SDO_RTR_PCTFREE set to 10, two-
dimensional data, and a geodetic SRID.
Answer: Run the following query:

SELECT
sdo_tune.estimate_rtree_index_size(200000 , 16384, 10, 2, 1)
FROM dual;






Practice 8-1: Indexing Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 50
6) Run the verify_indexes.sql script to check whether all the required indexes
were created. The script is located in the d:\labs\labs folder.
Answer: Run the script and check the output:
@d:\labs\labs\verify_indexes.sql

The output must be as shown in the following screenshot:



Note: The YP_SIDX index was imported with the YELLOW_PAGES table as part of
the classroom setup. You use this table in a later practice.

Oracle Spatial 11g: Essentials A - 51
Practices for Lesson 9
In this practice, you run spatial queries that apply some spatial operators such as
SDO_FILTER and SDO_ANYINTERACT. You view the output of some of the queries in
the MapViewer Simple Spatial Query Visualizer. You also run a query that uses the
SDO_GEOM.RELATE function.

Prerequisite: To perform this practice completely, you must have completed the practice
for lessons 2, 3, 5, 7, and 8 successfully.
If you did not complete the practices for lessons 2, 3, and 5, perform the steps mentioned
in the section titled Prerequisite for the remaining practices in the practice for lesson 6.
For this practice, you should have also completed the practice 7-1 successfully. If not, go
back to Practice 7-1 and perform the steps.
To catch up on Practice 8-1, at SQL *Plus prompt, enter the following command:
@d:\labs\catchup_scripts\create_indexes.sql


Oracle Spatial 11g: Essentials A - 52
Practice 9-1: Querying Spatial Data
1) From SQL*Plus, perform a primary filter query to find all counties that are likely to
interact with the state of New York. Use the geod_states and geod_counties
tables.
Answer: Run the following query to find all counties that are likely to interact with the
state of New York:
SELECT /*+ ordered */ county, c.state_abrv
FROM geod_states s,
geod_counties c
WHERE s.state = 'New York'
AND sdo_filter (c.geom, s.geom) = 'TRUE';

..

2) This exercise requires that OC4J is running and a connection is properly defined to
use MapViewer. If OC4J is not running, follow the directions in Practice 7 to start
OC4J and define a connection to the database. Use the MapViewer Simple Spatial
Query Visualizer to see the state of New York, and all counties that are likely to
interact with it.
Practice 9-1: Querying Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 53
Answer: Perform the following steps:
a) Click the start.bat batch file to start the OC4J server.
b) Open Internet Explorer. Assuming that you have defined the data source, go to the
URL: http://localhost:8888/mapviewer
c) Click the Demos tab.

d) Click jview.jsp. The Simple Spatial Query Visualizer page is displayed.
Ensure that the student data source is selected.

e) In the query 1: window, set the fill color to yellow and enter COUNTY in the Label
Column field. Enter the following query:
SELECT /*+ ordered */ c.geom
FROM geod_states s, geod_counties c
WHERE s.state='New York'
AND sdo_filter(c.geom, s.geom) = 'TRUE'
Note: Do not end the query with a semicolon.
f) In the query 2: window, set the line color to red and enter STATE in the Label
Column field. Enter the following query:
Practice 9-1: Querying Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 54
SELECT geom
FROM geod_states
WHERE state='New York'

g) Click the Submit button and view the map.

3) Find all counties interact with the state of New York.
Answer: Run the following query:

SELECT /*+ ordered */ county, c.state_abrv
FROM geod_states s,
geod_counties c
WHERE s.state = 'New York'
Practice 9-1: Querying Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 55
AND sdo_anyinteract (c.geom, s.geom) = 'TRUE';

..

4) Modify the query you wrote for question 2 to display only the counties that interact
with the state of New York.
Hint: Change SDO_FILTER in query 1 to SDO_ANYINTERACT.
Answer: Perform the following steps:
a) Enter the following query in the query1: window:
SELECT /*+ordered*/ c.geom
FROM geod_states s,
geod_counties c
WHERE s.state='New York'
AND SDO_ANYINTERACT(c.geom, s.geom) = 'TRUE'

Note: You can set the fill color to yellow and the label to COUNTY.
b) In the query 2 window, enter the following query:
SELECT geom
FROM geod_states
WHERE state='New York'

Note: You can set the line color to red and the label to STATE.
c) View the map.
Practice 9-1: Querying Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 56

5) Find all cities and the population of the cities in the rectangle that has a lower-left
coordinate of (109, 37) and an upper-right coordinate of (102, 40). Use the
geod_cities table.
Answer: Run the following query:

SELECT c.city, c.pop90
FROM geod_cities c
WHERE sdo_anyinteract(
c.location,
sdo_geometry (
2003, 8307, null,
sdo_elem_info_array (1,1003,3),
sdo_ordinate_array (-109, 37, -102, 40))
)= 'TRUE';


6) Find all counties and the population of each county that interact with the rectangle
that has a lower-left coordinate of (109, 37) and an upper-right coordinate of (102,
40).
Practice 9-1: Querying Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 57
Answer: Run the following query:
SELECT c.county, c.totpop
FROM geod_counties c
WHERE sdo_anyinteract
( c.geom,
sdo_geometry (2003, 8307, null,
sdo_elem_info_array (1,1003,3),
sdo_ordinate_array (-109, 37, -102, 40))
) = 'TRUE';


..

7) Determine the relationship between the state of New Hampshire and its counties. Set
the COL relation to A20.
Answer: Run the following query:
SELECT c.county,
sdo_geom.relate (s.geom,'DETERMINE', c.geom, 0.5)
"relation"
FROM geod_states s,
geod_counties c
WHERE s.state = 'New Hampshire'
AND s.state = c.state;
Practice 9-1: Querying Spatial Data (continued)
Oracle Spatial 11g: Essentials A - 58
Note: For formatted output, run col relation to a20 at the SQL prompt.




Oracle Spatial 11g: Essentials A - 59
Practices for Lesson 10
In this practice, you run queries that involve the SDO_NN, SDO_WITHIN_DISTANCE,
and SDO_JOIN operators.

Prerequisite: To perform this practice completely, you must have completed the practice
for lessons 2, 3, 5, 7, and 8 successfully.
If you did not complete or partially completed the practices for lessons 2, 3, 5, 7, and 8,
refer to the Prerequisite section in the practice for lesson 9.




Oracle Spatial 11g: Essentials A - 60
Practice 10-1: Using the SDO_WITHIN_DISTANCE, SDO_NN, and
SDO_JOIN Operators
1) Find cities within 100 miles of highway 'I10/I5'. Use the geod_interstates
and geod_cities tables.
Answer: Run the following query:
SELECT /*+ ordered */ c.city
FROM geod_interstates i,
geod_cities c
WHERE highway = 'I10/I5'
AND sdo_within_distance (c.location, i.geom, 'distance=100
unit=mile') = 'TRUE';


2) Find the five nearest cities and their distances nearest to highway 'I170'. Order by
distance in miles.
Answer: Run the following query:
SELECT /*+ ORDERED */
c.city,
sdo_nn_distance (1) distance_in_miles
FROM geod_interstates i,
geod_cities c
WHERE i.highway = 'I170'
AND sdo_nn(c.location, i.geom,
'sdo_num_res=5 unit=mile', 1) = 'TRUE'
ORDER BY distance_in_miles;
Practice 10-1: Using the SDO_WITHIN_DISTANCE, SDO_NN, and
SDO_JOIN Operators (continued)
Oracle Spatial 11g: Essentials A - 61


3) Find the five cities nearest to highway 'I170' whose population is greater than
300,000, and return their distance to highway 'I170'.
Answer: Run the following query:
SELECT /*+ ordered */
c.city,
sdo_nn_distance (1) distance_in_miles
FROM geod_interstates i,
geod_cities c
WHERE i.highway = 'I170'
AND sdo_nn (c.location, i.geom,
'sdo_batch_size=5 unit=mile', 1) = 'TRUE'
AND pop90 > 300000
AND rownum < 6
ORDER by distance_in_miles;


4) Find all city-and-county pairs that interact.
Answer: Run the following query:
SELECT /*+ ordered use_nl(a,b) use_nl(a,c)*/
b.city, c.county
FROM TABLE(SDO_JOIN(
'GEOD_COUNTIES', 'GEOM',
'GEOD_CITIES', 'LOCATION',
'MASK=ANYINTERACT')) a,
geod_cities b,
geod_counties c
WHERE a.rowid1 = c.rowid
AND a.rowid2 = b.rowid
ORDER BY b.city;
Practice 10-1: Using the SDO_WITHIN_DISTANCE, SDO_NN, and
SDO_JOIN Operators (continued)
Oracle Spatial 11g: Essentials A - 62

..

5) Find all cities within 20 miles of all interstate highways.
Answer: Run the following query:
SELECT /*+ ordered */ a.city, b.highway
FROM TABLE(SDO_JOIN(
'GEOD_INTERSTATES', 'GEOM',
'GEOD_CITIES', 'LOCATION',
'DISTANCE=20 UNIT=MILE')) c,
geod_cities a,
geod_interstates b
WHERE c.rowid1 = b.rowid
AND c.rowid2 = a.rowid
ORDER BY a.city;


..



Oracle Spatial 11g: Essentials A - 63
Practices for Lesson 11
In this practice, you solve queries by using the area, length, and distance calculation
functions such as SDO_AREA, SDO_LENGTH, and SDO_DISTANCE. You run queries to
perform buffer operations. You also work on spatial Boolean queries.

Prerequisite: To perform this practice completely, you must have completed the
practices for lessons 2, 3, 5, 7, and 8 successfully.
If you did not, refer to the Prerequisite section in the practice for lesson 9.



Oracle Spatial 11g: Essentials A - 64
Practice 11-1: Analyzing Geometries by Using Spatial Operators
and Functions
1) Find the sum of the area in square miles of all counties around Passaic County in New
Jersey.
Answer: Run the following query:
SELECT /*+ ordered */ sum (sdo_geom.sdo_area (c1.geom, 0.5,
'unit=sq_mile')) area
FROM geod_counties c2,
geod_counties c1
WHERE c2.state = 'New Jersey'
AND c2.county = 'Passaic'
AND sdo_relate (c1.geom, c2.geom, 'mask=TOUCH
querytype=WINDOW') = 'TRUE';


2) Find the sum of the area in square miles of all counties around Passaic County in New
Jersey, categorized by state.
Answer: Run the following query:
SELECT /*+ ordered */ c1.state,
SUM (sdo_geom.sdo_area(c1.geom, 0.5, 'unit=sq_mile'))
area
FROM geod_counties c2,
geod_counties c1
WHERE c2.state = 'New Jersey'
AND c2.county = 'Passaic'
AND SDO_RELATE (c1.geom, c2.geom, 'mask=TOUCH
querytype=WINDOW') = 'TRUE'
GROUP BY c1.state;


3) Find all states with a population density over 500 per square mile, and display the
area of each state in square kilometers. Round off the population density.
Answer: Run the following query:
SELECT state,
ROUND (poppsqmi) poppsqmi,
sdo_geom.sdo_area (geom, 0.5, 'unit=sq_km') area
FROM geod_states
WHERE poppsqmi > 500;
Practice 11-1: Analyzing Geometries by Using Spatial Operators
and Functions (continued)
Oracle Spatial 11g: Essentials A - 65


4) Find all states with borders longer than 1,500 miles, and return the length of each
border.
Answer: Run the following query:
SELECT a.state, a.length
FROM (SELECT state,
sdo_geom.sdo_length (geom, 0.5, 'unit=mile') length FROM
geod_states) a
WHERE a.length > 1500;


5) Calculate the minimum distance between the highway I170 and Passaic County in
miles.
Answer: Run the following query:
SELECT SDO_GEOM.SDO_DISTANCE (a.geom, b.geom, 0.5,
'unit=mile') distance
FROM geod_interstates a,
geod_counties b
WHERE b.county = 'Passaic' and b.state_abrv = 'NJ'
AND a.highway = 'I170';




Practice 11-1: Analyzing Geometries by Using Spatial Operators
and Functions (continued)
Oracle Spatial 11g: Essentials A - 66
6) Generate a thirty-kilometer buffer around Interstate I95.
Answer: Run the following query:
SELECT sdo_geom.sdo_buffer
(geom, 30, 0.5, 'arc_tolerance=0.05 unit=km')
buffer_geom
FROM geod_interstates
WHERE highway = 'I95';

7) Find all counties that have any interaction with a thirty-kilometer buffer around
highway I95.
Answer: Run the following query:
SELECT /*+ ordered */ c.county
FROM geod_interstates i,
geod_counties c
WHERE i.highway = 'I95'
AND sdo_anyinteract (c.geom,
sdo_geom.sdo_buffer (i.geom, 30, 0.5, 'ARC_TOLERANCE=0.05
UNIT=KILOMETER')) = 'TRUE';

..

8) In the geom_data table, insert two optimized rectangles by using the following
values:
i) Object_id: 20
ii) Name: Rectangle1
iii) Coordinates: (5,5), (9,11)

i) Object_id: 21
ii) Name: Rectangle2
iii) Coordinates: (8,8), (12,14)
Practice 11-1: Analyzing Geometries by Using Spatial Operators
and Functions (continued)
Oracle Spatial 11g: Essentials A - 67
Answer: To insert two optimized rectangles, run the following INSERT statements:
INSERT INTO geom_data VALUES(
20,'Rectangle1',
SDO_GEOMETRY( 2003, NULL, NULL,
SDO_ELEM_INFO_ARRAY(1,1003, 3),
SDO_ORDINATE_ARRAY(5,5, 9,11))
);

INSERT INTO geom_data VALUES(
21,'Rectangle2',
SDO_GEOMETRY(2003, NULL, NULL,
SDO_ELEM_INFO_ARRAY(1,1003, 3),
SDO_ORDINATE_ARRAY(8,8, 12,14))
);
9) View the two inserted rectangles in MapViewer.
Answer: To view the rectangles, run the following queries:
a) In the query1 window, enter the following query:
SELECT shape from geom_data where object_id=20
b) In the query2 window, enter the following query:
SELECT shape from geom_data where object_id=21
Practice 11-1: Analyzing Geometries by Using Spatial Operators
and Functions (continued)
Oracle Spatial 11g: Essentials A - 68
Note: Change the fill color for the first query to yellow and for the second query to red.
Make sure that the Label column field for both query windows is empty.



10) Now, perform a UNION operation on the two rectangles. The query should return the
geometry object that is a topological union of the two rectangles. View the result in
MapViewer.
Answer: Enter the following query in the query1: window:
SELECT sdo_geom.sdo_union(
a.shape, b.shape, 0.5)
FROM geom_data a,
geom_data b
WHERE a.object_id = 20
AND b.object_id = 21;


Practice 11-1: Analyzing Geometries by Using Spatial Operators
and Functions (continued)
Oracle Spatial 11g: Essentials A - 69




Oracle Spatial 11g: Essentials A - 70
Practices for Lesson 12
In this practice, you solve spatial queries by using the analysis, MBR, utility, and
aggregate functions.

Prerequisite: To perform this practice completely, you must have completed the
practices for lessons 2, 3, 5, 7, and 8 successfully.
If you did not, refer to the Prerequisite section in the practice for lesson 9.


Oracle Spatial 11g: Essentials A - 71
Practice 12-1: Using Spatial Analysis, MBR, Utility, and
Aggregate Functions
1) Write a query to find the centroid (or center of gravity) of the state of Texas.
Answer: Run the following query:
SELECT sdo_geom.sdo_centroid(c.geom, 0.5) centroid
FROM geod_states c
WHERE c.state = 'Texas';


2) Write a query to generate the minimum bounding rectangle of the state of Texas.
Answer: Run the following query:
SELECT sdo_geom.sdo_mbr(c.geom) mbr
FROM geod_states c
WHERE c.state = 'Texas';


3) Write a query to find the number of vertices and number of elements in the geometry
for the state of Texas.
Answer: Run the following query:
SELECT sdo_util.getnumelem(a.geom),
sdo_util.getnumvertices(a.geom)
FROM geod_states a
WHERE a.state='Texas';


4) From the GEOD_STATES(GEOM) layer, generate a geometry that represents the
union of the following states: NH,VT, and NY. View the results in MapViewer.
Answer: Perform the following steps:
a) Enter the following query in query1: window. Set the fill color to yellow.
SELECT sdo_aggr_union(
sdoaggrtype(a.geom, 0.5)) cow_states
FROM geod_states a
WHERE a.state_abrv in ('NH', 'VT', 'NY')

Practice 12-1: Using Spatial Analysis, MBR, Utility, and
Aggregate Functions (continued)
Oracle Spatial 11g: Essentials A - 72
b) Enter the following query in query2: window. Set the line color to red.
SELECT geom
FROM geod_counties a
WHERE a.state_abrv in ('NH', 'VT', 'NY')

5) From the GEOD_STATES(GEOM)layer, find the centroid of the following New
England states: MA, NH, VT, RI, CT, and ME. View the results in MapViewer.
Answer: Perform the following steps:
a) Enter the following query in the query1: window:
SELECT sdo_aggr_centroid(
sdoaggrtype(a.geom, 0.5))
FROM geod_states a
WHERE a.state_abrv in ('MA', 'NH', 'VT', 'CT', 'RI', 'ME')
b) Enter the following query in the query2: window.
SELECT geom
FROM geod_counties a
WHERE a.state_abrv in ('NH', 'MA', 'RI', 'VT', 'CT', 'ME')
Practice 12-1: Using Spatial Analysis, MBR, Utility, and
Aggregate Functions (continued)
Oracle Spatial 11g: Essentials A - 73

6) From the GEOD_STATES(GEOM)layer, find the geometry that forms a convex hull
around the following New England states: MA, NH, VT, RI, CT, and ME. View the
results in MapViewer.
Answer: Perform the following steps:
a) Enter the following query in the query1: window:
SELECT sdo_aggr_convexhull(sdoaggrtype(a.geom, 0.5))
FROM geod_counties a
WHERE a.state_abrv in ('MA', 'NH', 'VT', 'RI', 'CT', 'ME');
b) Enter the following query in the query2: window. Set the line color to black and
fill color to red.
SELECT geom
FROM geod_counties a
WHERE a.state_abrv in ('NH', 'MA', 'RI', 'VT', 'CT', 'ME');
Practice 12-1: Using Spatial Analysis, MBR, Utility, and
Aggregate Functions (continued)
Oracle Spatial 11g: Essentials A - 74



Oracle Spatial 11g: Essentials A - 75
Practices for Lesson 13
In this practice, you get a thorough hands-on practice with the Map Builder tool. In this
practice, you create themes and then associate them with a base map. Then you use a
mapclient JSP demo to publish the map to the Web. For this practice, you must access
mapbuilder_10131.zip located in the D:\labs\software folder.

Prerequisite: To perform this practice completely, you must have completed the
practices for lessons 2, 3, 5, 7, and 8 successfully.
If you did not, refer to the Prerequisite section in the practice for lesson 9.



Oracle Spatial 11g: Essentials A - 76
Practice 13-1: Defining Maps by Using the Map Builder Tool

Part 1

As part of this course, many styles are supplied in the Oracle Data Pump format in the
D:\labs\data\styles.dmp file.
1) Assuming that you created a directory object, student_dumpdir, in the previous
lesson practice, import the styles.dmp file by using impdp.
Answer: To import the styles.dmp file, perform the following steps:
a) Open a command window and enter the following:
impdp student/student dumpfile=student_dumpdir:styles.dmp
nologfile=y


2) Move the contents of the styles table that you imported into USER_SDO_STYLES.
Commit the records.
Answer: Perform the following steps:
a) Assuming that you have logged in as student in SQL*Plus, run the following
INSERT statement:
INSERT INTO user_sdo_styles SELECT * FROM styles;
COMMIT;


3) For this practice, you must extract the mapbuilder_10131.zip file into a new
folder under the root D drive: D:\. The mapbuilder_10131.zip file is placed
in the D:\labs\software folder. Create a new directory, mapbuilder, under
D:\ and extract the zip file there.
Answer: Perform the following steps:
a) Create the mapbuilder directory under D:\.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 77
b) Double-click the mapbuilder_10131.zip file to open WinZip. Click
Extract. Choose D:\mapbuilder as the location to extract the files into.
4) Start MapBuilder and establish a database connection.
Answer: Perform the following steps:
a) Open a new command prompt, and change to the D:\mapbuilder folder.
b) To start Map Builder, run the following command:
java -jar mapbuilder.jar
c) The Oracle Map Builder interface opens, as shown in the following screenshot:

d) To create a database connection, from the File menu, select New Connection. In
the Add Connection dialog box, enter the following values:
i) Connection Name: student
ii) Host: localhost
iii) Port: 1521
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 78
iv) SID: orcl
v) Driver: thin
vi) User: student
vii) Password: student
e) Click OK.

f) The Connection drop-down box shows the student connection, as shown in the
following screenshot:
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 79


Part 2
5) A theme is analogous to a geometry column. Start the Create Geometry Theme
Wizard.
i) Create a theme definition called STATES that represents the
GEOD_STATES(geom) layer.
ii) Select the STUDENT:C.US MAP YELLOW render style. Select the
STUDENT:T.STATE NAME text style for the label column, STATE_ABRV.
iii) Preview the STATES theme.
Answer: Perform the following steps:
a) In Map Builder, right-click Themes, and select Create Geometry Theme to
display the Create Geometry Theme Wizard. Click Next on the first page.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 80

b) Create a theme definition called STATES that represents the GEOD_STATES
(geom)layer. Enter STATES in the Name field and select the GEOD_STATES
table from the Base Table drop-down list. Click Next.

c) For Style Type set to Color, click Select. From the Style Picker dialog box, select
the STUDENT:C.US MAP YELLOW render style. Click OK. Click Next.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 81

d) Enable Label Style. Select Text for Style Type. Click Select. In the Style Picker
dialog box, select the STUDENT:T.STATE NAME text style for the label
column. Click OK.
e) In the Attribute drop-down list, select STATE_ABRV as the label column. Set the
Label Func to 1 to display the label column.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 82

f) Click Next until you see the Finish button. Examine the XML code that Map
Builder inserts into USER_SDO_GEOM_THEMES when you click Finish.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 83

g) Click Finish to exit the Create Geometry Theme Wizard.
h) Expand Themes > Geometry Themes. Right-click STATES and select Preview.
Press the green arrow ( ) to start previewing. You can zoom in or out to
preview.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 84

6) Create another theme named COUNTIES that represents the GEOD_COUNTIES
(geom)layer.
i) Select the STUDENT:C.BLACK GRAY render style.
ii) Select the STUDENT:T.STATE NAME text style for the label column,
COUNTY.
iii) Preview the COUNTIES theme through Map Builder.
Answer: Perform the following steps:
a) In Map Builder, right-click Themes and select Create Geometry Theme to
display the Create Geometry Theme Wizard. Click Next on the first page.
b) Create a theme definition called COUNTIES that represents the
GEOD_COUNTIES(geom)layer. Enter COUNTIES in the Name field and select
the GEOD_COUNTIES table from the Base Table drop-down list. Click Next.
c) For Style Type set to Color, click Select. From the Style Picker dialog box, select
the STUDENT:C.BLACK GRAY render style. Click OK. Click Next.
d) Enable Label Style. Select Text for Style Type. Click Select. In the Style Picker
dialog box, select the STUDENT:T.STATE NAME text style for the label
column. Click OK.
e) In the Attribute drop-down list, select COUNTY as the label column. Set the Label
Func to 1 to display the label column.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 85

f) Click Next until you see the Finish button. View the XML code that Map Builder
will insert into USER_SDO_GEOM_THEMES when you click Finish.
g) Click Finish to exit the Create Geometry Theme Wizard.
h) Expand Themes > Geometry Themes. Right-click COUNTIES and select
Preview. Press the green arrow ( ) to start previewing. You can zoom in or out
to preview.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 86

7) A map can be associated with one or more themes. Create a map definition called
SAMPLE_MAP.
i) Add the STATES theme to SAMPLE_MAP. Set max_scale to 12,000,000.
ii) Add the COUNTIES theme to SAMPLE_MAP. Set min_scale to
12,000,000.
iii) Preview the SAMPLE_MAP map through Map Builder.
Answer: Perform the following steps:
a) In Map Builder, right-click Base Maps and select Create Base Map to start the
Create Base Map Wizard. Click Next on the first page.
b) Enter SAMPLE_MAP in the name field. Click Next.
c) Add the STATES theme to SAMPLE_MAP. Also, add the COUNTIES theme to
SAMPLE_MAP. Select the theme from the Theme Names box and click the first
button (highlighted in the screenshot) to add the theme to SAMPLE_MAP.
d) Make the STATES theme render until you zoom in to a scale of 1:12,000,000, and
then turn it off (set max_scale to 12,000,000).
e) Make the COUNTIES theme render any time that you zoom in more than a scale
of 1:12,000,000 (set min_scale to 12,000,000).
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 87

f) Click Next to see the XML that Map Builder will insert into
USER_SDO_GEOM_MAPS when you click Finish.
g) Click Finish to exit the Create Base Map Wizard.
h) To preview the SAMPLE_MAP map through Map Builder, expand Base Maps.
Right-click SAMPLE_MAP and select Preview.
i) Click the green arrow to preview. You can zoom in or out to preview.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 88

8) Now you are ready to publish maps to the Web. MapViewer includes a JSP demo to
help you get started. View the SAMPLE_MAP that you created earlier.
Answer: Perform the following steps:
a) From the MapViewer page, click the Demos tab. Click the mapclient demo.
b) Populate the following fields:
i) MapViewer URL: http://localhost:8888/mapviewer/omserver
ii) Data Source: student
iii) Title: Sample Map (optional)
iv) Base Map: sample_map
v) Map Center X Coord: -70
vi) Map Center Y Coord: 42
vii) Map Size: 10
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 89
Note: Prior to Ratio Scale, a different mechanism called Map Size was used. Map
Size is no longer recommended, but the version of mapclient.jsp that ships
with MapViewer 10.1.3.1 still expects Map Size, and not Ratio Scale. Map Size is
the distance from the north to south in the map display. In this example, it would
be 10 degrees north to south.

c) Click Submit. You can recenter it by clicking the new map center location. Try
out the Zm In, Zm Out, Pan W., Pan N., Pan S., and Pan E. buttons.
d) Click Zm Out until you see the complete US Map with state names.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 90

e) Now keep clicking ZM In.
Practice 13-1: Defining Maps by Using the Map Builder Tool
(continued)
Oracle Spatial 11g: Essentials A - 91

f) View the XML map request submitted by the JSP in the Request/Response/Msg
window.




Oracle Spatial 11g: Essentials A - 92
Practices for Lesson 14
In this practice, you set up and run Oracle Maps demos. For this practice, you use a zip
file called mvdemo_10131.zip placed in the D:\labs\software folder.

Prerequisite: To perform this practice completely, you must have completed the
practices for lessons 7 and 13.



Oracle Spatial 11g: Essentials A - 93
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API
1) From Windows Explorer, extract mvdemo_10131.zip to the local disk (the root
directory on the D: drivethat is, D:\.). When you extract the file, it creates the
D:\mvdemo directory.
Answer: Perform the following steps:
a) From Windows Explorer, double-click mvdemo_10131.zip to start WinZip
and extract it to the local disk (the root directory on the D: drive is D:\).
b) Click Extract. Enter D:\ in the Extract to field of the pop-up menu. Click Extract.
When you extract the file, it creates the D:\mvdemo directory.
2) Connect using system/oracle as the username/password. Create an mvdemo
user identified by mvdemo. Grant connect, resource, and create view privileges to the
mvdemo user.
Answer: Perform the following:
a) In SQL*Plus, connect using system/oracle as the username/password and
run the following command:
conn system/oracle
GRANT connect, resource, create view TO mvdemo IDENTIFIED BY
mvdemo;
3) Import the mvdemo.dmp file. It is located in the D:\mvdemo folder.
Answer: To import the mvdemo.dmp file, at the command prompt, enter the following
command:
imp mvdemo/mvdemo file=d:\mvdemo\mvdemo.dmp full=y ignore=y
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 94

4) Log in as the mvdemo user in SQL*Plus and run the mvdemo.sql script.
Answer: Run the following:
conn mvdemo/mvdemo
@d:\mvdemo\mvdemo.sql
5) Through the MapViewer admin page, configure a data source for the MapViewer
demos. Name the data source MVDEMO. Create the data source in a way that
automatically starts when MapViewer starts.
Answer: Perform the following steps:
a) Make sure that the MapViewer is running in the OC4J console. If not, double-
click the start.bat file in the D:\mv10131_qs directory.
b) Start Internet Explorer and enter the following URL:
http://localhost:8888/mapviewer/
c) On the upper-right corner of the MapViewer page, click Admin. Log in as the
oc4jadmin user and enter welcome as the password.
d) Under the Management tab, select Configuration under Manage MapViewer.
e) At the bottom of the configuration file, either uncomment the example
map_data_source element or if you modified it in Practice 7-1, copy and
paste the map_data_source element and modify the following values:
i) Name: mvdemo
ii) Host: localhost
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 95
iii) Port: 1521
iv) Sid: orcl
v) User: mvdemo
vi) Password:!mvdemo
vii) # Mappers: 3

f) Click Save & Restart. Click the Datasources link under Manage MapViewer.
The mvdemo data source should be listed under Existing data sources.
6) Create the USER_SDO_CACHED_MAPS and ALL_SDO_CACHED_MAPS metadata
views. This is a one-time task. Note that in a future release of Oracle Database, these
metadata views will be created automatically when Oracle Locator or Oracle Spatial
is installed.
Answer: Perform the following steps:
a) Log in using system/oracle as the username/password.
conn system/oracle
b) Run the following SQL script.
@d:\mv10131_qs\oc4j\j2ee\home\applications\mapviewer\web\
WEB-INF\admin\mcsdefinition.sql;
7) From the MapViewer Admin page, create a cache map instance for the DEMO_MAP
base map, which was loaded when mvdemo.dmp was imported.
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 96
Answer: Perform the following steps:
a) From the MapViewer Admin page, click the Management tab, and select
Manage Map Caches and Create. The Select type of map source menu must
be set to Internal.

b) Click Continue. Enter the following values:
i) Name: DEMO_MAP
ii) Data source: mvdemo
iii) Base map: DEMO_MAP
iv) # Zoom Levels: 10
v) Minimum map size: 1000
vi) Maximum map size: 25000000
vii) SRID: 8307
viii) Min X: -180
ix) Max X: 180
x) Min Y: -90
xi) Max Y: 90
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 97

c) Click Submit.
8) Now you can run some of the Oracle Maps demos. You can try some of the
following:
i) maps and faces
ii) Display Map
iii) Navigation Panel
iv) Theme Based FOI layer visibility
v) Red Lining
vi) Scale Bar
vii) Circle Tool
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 98
viii) Collapsible Overview Map
ix) Marquee Zoom
x) Move FOI
Answer: To run some of the Oracle Maps demos, perform the following steps:
a) From the MapViewer Web page, click the Demos tab.
b) At the bottom of the page, click the Oracle Maps tutorial. Click Running the
demos.

c) Each demo is interactive, and the source code is displayed if you scroll to the
bottom.
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 99

9) You can create a map cache instance for any base map defined in USER_SDO_MAPS.
From the MapViewer Admin page, create a cache map instance for the
SAMPLE_MAP base map that you created in the lesson titled Defining Maps by
Using the Map Builder Tool.
Answer: Perform the following:
a) From the MapViewer Admin page, click the Management tab, and select
Manage Map Caches and Create. The Select type of map source menu must
be set to Internal. Click Continue.
b) Enter the following values:
i) Name: SAMPLE_MAP_CACHE
ii) Data Source: student
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 100
iii) Base map: SAMPLE_MAP
iv) # Zoom Levels: 10
v) Minimum map size: 1000
vi) Maximum map size: 25000000
vii) SRID: 8307
viii) Min X: -180
ix) Max X: 180
x) Min Y: -90
xi) Max Y: 90
c) Click submit.
10) Oracle MapViewer ships with a demo to test map cache instances that you create. The
demo is called OMaps. Test the SAMPLE_MAP_CACHE map cache instance by
running the OMaps demo.
Answer: Perform the following steps:
a) From the MapViewer Web page, click the Demos tab.
b) Click the OMaps demo.
c) Enter the following values:
i) Datasource: student
ii) Cached Base Map: sample_map_cache
iii) Center_x: -122.4
iv) Center_y: 37.8
v) Initial Zoom Level: 4
vi) Map width: 800
vii) Map height: 600
Practice 14-1: Leveraging Oracle Maps: The Map Cache and
JavaScript API (continued)
Oracle Spatial 11g: Essentials A - 101

d) Click Proceed. Now, you can try out the demo. Click the controls on the map
(highlighted by the red rectangle in the screenshot) to zoom in or out or move to a
particular location on the map.


Oracle Spatial 11g: Essentials A - 102
Practices for Lesson 15




Oracle Spatial 11g: Essentials A - 103
Practice 15-1: Creating a User-Defined Coordinate System

No practice in this lesson.



Oracle Spatial 11g: Essentials A - 104
Practices for Lesson 16
In this practice, you linear-reference geometries and use some SDO_LRS package
functions. You also run dynamic segmentation queries.
Prerequisite: To perform this practice completely, you must have completed the
practices for lessons 2, 3, 5, 7, and 8 successfully.
If you did not, refer to the Prerequisite section in the practice for lesson 9.


Oracle Spatial 11g: Essentials A - 105
Practice 16-1: Implementing a Linear Referencing System
In this practice, it is assumed that you are connected as student.
1) Using data from the GEOD_INTERSTATES table, create an LRS_HIGHWAYS table.
The following is the structure of the LRS_HIGHWAYS table:
i) Highway varchar2(35)
ii) Geom. sdo_geometry
Answer: To create the LRS_HIGHWAYS table, run the following statement:

CREATE TABLE lrs_highways (
highway VARCHAR2(35),
geom SDO_GEOMETRY);
2) The LRS_HIGHWAYS table contains highways that interact with the state of
Delaware (DE), but are clipped at the DE border. Write a query to clip highways at
the DE border, and insert the clipped geometries into the LRS_HIGHWAYS table.
Answer: Run the following query:

INSERT INTO lrs_highways
SELECT /*+ ordered */
b.highway,
sdo_geom.sdo_intersection(a.geom, b.geom, 0.5) geom
FROM geod_states a,
geod_interstates b
WHERE a.state_abrv = 'DE'
AND SDO_ANYINTERACT(b.geom, a.geom) = 'TRUE';


3) Insert 2D metadata for the new layer you created, LRS_HIGHWAYS(geom), into the
USER_SDO_GEOM_METADATA view.
Answer: To insert metadata, run the following query:
INSERT INTO user_sdo_geom_metadata
VALUES (
'LRS_HIGHWAYS', 'GEOM',
sdo_dim_array (
sdo_dim_element ('Long', -180, 180, 0.5),
sdo_dim_element ('Lat', -90, 90, 0.5)),
8307);
Practice 16-1: Implementing a Linear Referencing System
(continued)
Oracle Spatial 11g: Essentials A - 106
4) Linear-reference all geometries in the LRS_HIGHWAYS (geom) layer. Also,
confirm that the metadata was updated.
Answer: Execute the following PL/SQL block of code:
set serveroutput on;
declare
status varchar2(32);
begin
status := SDO_LRS.CONVERT_TO_LRS_LAYER('LRS_HIGHWAYS','GEOM',
0, 1000000, 0.5);
dbms_output.put_line('Status = '||status);
end;

SELECT *
FROM user_sdo_geom_metadata
WHERE table_name = 'LRS_HIGHWAYS'
AND column_name = 'GEOM';

Note: The geometries in LRS_HIGHWAYS were linear-referenced with
SDO_LRS.CONVERT_TO_LRS_LAYER. Each geometrys start measure was set to 0,
and each geometrys end measure was set to the geometry length. For geodetic
geometries, the length is in meters. For nongeodetic geometries, the length is in the
coordinate system unit.
5) Create an index on the LRS_HIGHWAYS(highway)column.
Answer: To create an index, run the following query:
CREATE INDEX lrs_highway_idx ON LRS_HIGHWAYS (highway);
6) Find the length of each highway in DE. Specify the length in meters.
Answer: To find the length of each highway in DE, run the following query:
SELECT highway,
SDO_LRS.GEOM_SEGMENT_END_MEASURE(geom)
"LENGTH_IN_METERS"
FROM lrs_highways;





Practice 16-1: Implementing a Linear Referencing System
(continued)
Oracle Spatial 11g: Essentials A - 107
7) Create a table called PAVEMENT_CONDITION for storing the pavement conditions
associated with highway segments in DE. The PAVEMENT_CONDITION table must
not contain geometries, but only the measure values associated with the linear-
referenced geometries in LRS_HIGHWAYS. The following is the structure of the
table:
i) highway varchar2(35)
ii) from_measure number
iii) to_measure number
iv) condition varchar2(6)
Answer: To create the PAVEMENT_CONDITION table, run the following query:
CREATE TABLE pavement_condition (
highway varchar2(35),
from_measure number,
to_measure number,
condition varchar2(6));
8) Insert records with highway-segment pavement conditions into the
PAVEMENT_CONDITION table. Use the following values:
i) 'I95', 0, 5951.5, 'good'
ii) 'I95', 5951.5, 28000, 'fair'
iii) 'I95', 28000, 37194, 'poor'
iv) 'I495', 0, 16001, 'good'
v) 'I495', 16001, 18004, 'poor'
vi) 'I295', 0, 3000, 'poor'
vii) 'I295', 3000, 4000, 'fair'
viii) 'I295', 4000, 8001.5, 'poor'
ix) 'I295', 8001.5, 9603, 'good'

Answer: To insert the records, run the following INSERT statements (Use the
sol_16_08.sql script located in d:\labs\soln folder):
insert into pavement_condition values (
'I95', 0, 5951.5, 'good');
insert into pavement_condition values (
'I95',5951.5 , 28000, 'fair');
insert into pavement_condition values (
'I95', 28000, 37194, 'poor');
insert into pavement_condition values (
'I495', 0, 16001, 'good');
insert into pavement_condition values (
Practice 16-1: Implementing a Linear Referencing System
(continued)
Oracle Spatial 11g: Essentials A - 108
'I495', 16001, 18004, 'poor');
insert into pavement_condition values (
'I295', 0, 3000, 'poor');
insert into pavement_condition values (
'I295', 3000, 4000, 'fair');
insert into pavement_condition values (
'I295', 4000, 8001.5, 'poor');
insert into pavement_condition values (
'I295', 8001.5, 9603, 'good');
commit;
9) Create an index on the PAVEMENT_CONDITION(highway)column.
Answer: To create an index, run the following statement:
CREATE INDEX pavement_condition_idx on pavement_condition
(highway);
10) Dynamically generate the clipped sections of highways in DE that have poor
pavement condition. This operation is also known as dynamic segmentation. Use the
PAVEMENT_CONDITION table to clip and return the highway segments where the
pavement condition is poor.
Hint: Join the PAVEMENT_CONDITION and LRS_HIGHWAYS tables.
Answer: Run the following query to perform dynamic segmentation:
SELECT sdo_lrs.clip_geom_segment(
a.geom, b.from_measure, b.to_measure), a.highway
FROM lrs_highways a,
pavement_condition b
WHERE b.condition = 'poor'
AND a.highway = b.highway;
11) From the beginning of the I95 highway, traverse 3,000 meters and return the
longitude and latitude at that location.
Answer: Run the following query:
SELECT sdo_lrs.locate_pt(a.geom, 3000, 0)
FROM lrs_highways a
WHERE highway = 'I95';







Practice 16-1: Implementing a Linear Referencing System
(continued)
Oracle Spatial 11g: Essentials A - 109
12) Find the measure position along highway I295 nearest to the following location:
(75.59, 39.70).
Answer: Run the following query:
SELECT sdo_lrs.find_measure( a.geom,
sdo_geometry(2001, 8307, NULL,
sdo_elem_info_array(1,1,1),
sdo_ordinate_array(-75.59, 39.70)))
"Distance_along_I295_meters"
FROM lrs_highways a
WHERE highway = 'I295';




Oracle Spatial 11g: Essentials A - 110
Practices for Lesson 17
In this practice, you have a few practice questions on spatial index partitioning and a set
of questions on function-based indexes. In this practice, you also import a transportable
tablespace containing the ADCI sample data that will be used in the forthcoming
practices.
Prerequisite: To perform this practice completely, you must have completed the
practices for lessons 2, 3, 5, 7, and 8 successfully.
If you did not, refer to the Prerequisite section in the practice for lesson 9.


Oracle Spatial 11g: Essentials A - 111
Practice 17-1: Managing Spatial Indexes
Using partitioned spatial index
1) A non-partitioned table of fabricated yellow pages data called YELLOW_PAGES has
been loaded in your schema, student. Create a partitioned table called
YELLOW_PAGES_PART by selecting all the data from the YELLOW_PAGES table,
and use the CATEGORY column as the partition key for YELLOW_PAGES_PART.
The CATEGORY column can contain the following values. Place each category in its
own partition.
i) Category 1: restaurants
ii) Category 2: banks
iii) Category 3: gas stations
iv) Category 4: grocery stores
v) Category 5: hotels
vi) Category 6: auto dealers
Answer: To create a partitioned table, run the following query:
CREATE TABLE yellow_pages_part
PARTITION BY RANGE (category)
(PARTITION p1 VALUES LESS THAN (2),
PARTITION p2 VALUES LESS THAN (3),
PARTITION p3 VALUES LESS THAN (4),
PARTITION p4 VALUES LESS THAN (5),
PARTITION p5 VALUES LESS THAN (6),
PARTITION p6 VALUES LESS THAN (MAXVALUE))
AS SELECT id,
name,
category,
location
FROM yellow_pages;
2) Insert metadata for the partitioned YELLOW_PAGES_PART (location) column
into the USER_SDO_GEOM_METADATA view. Set the tolerance to 1/10th of a meter
for the geodetic layer.
Answer: Run the following query to update the metadata:
INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID) VALUES
('YELLOW_PAGES_PART', 'LOCATION',
SDO_DIM_ARRAY (
SDO_DIM_ELEMENT('X', -180.0, 180.0, 0.1),
SDO_DIM_ELEMENT('Y', -90.0, 90.0, 0.1)),
8307);
3) Create a partitioned spatial index on YELLOW_PAGES_PART (location). The
table contains 360,600 rows. The spatial index may take several minutes to create. Set
LAYER_GTYPE=POINT.
Practice 17-1: Managing Spatial Indexes (continued)
Oracle Spatial 11g: Essentials A - 112
Answer: Run the following query to create a partitioned spatial index:
CREATE INDEX yellow_pages_part_sidx on yellow_pages_part
(location)
indextype is mdsys.spatial_index parameters
('LAYER_GTYPE=POINT')
LOCAL
(partition ip1,
partition ip2,
partition ip3,
partition ip4,
partition ip5,
partition ip6);
4) In the current SQL*Plus session, enter SET TIMING ON. Determine the number of
restaurants (CATEGORY=1) that are within eight miles of the location (73.8, 40.7)
using the YELLOW_PAGES table and from the YELLOW_PAGES_PART table.
Compare the query times on the nonpartitioned and partitioned tables.
i) Note: Try running this test a second time. The first time you ran the test, it
included the time to cache disk blocks into memory (query returns 9,231
rows). The second time you run the test, it performs the query from cached
disk blocks.
ii) Set the timing off.
Answer: Perform the following steps:
a) Set the timing:
SET TIMING ON
b) First, run the query by using the nonpartitioned table:
SELECT count(*)
FROM yellow_pages a
WHERE sdo_within_distance (a.location,
sdo_geometry (2001, 8307,
sdo_point_type (-73.8, 40.7, null), null, null),
'distance=8 unit=mile') = 'TRUE'
AND category = 1;
c) Now, run the query by using the partitioned table:
SELECT count(*)
FROM yellow_pages_part a
WHERE sdo_within_distance (a.location,
sdo_geometry (2001, 8307,
sdo_point_type (-73.8, 40.7, null), null, null),
'distance=8 unit=mile') = 'TRUE'
AND category = 1;
d) Set the timing off:
SET TIMING OFF
Practice 17-1: Managing Spatial Indexes (continued)
Oracle Spatial 11g: Essentials A - 113



Note: The timings may differ on your machine depending on the machines
configuration and performance.
5) Query the YELLOW_PAGES_PART table to get the three closest businesses to the
location (73.8042, 40.7613). Display the business name and distance in miles.
Answer: Run the following query:
SELECT name, distance
FROM (SELECT name, sdo_nn_distance(1) distance
FROM yellow_pages_part a
WHERE sdo_nn (a.location,
sdo_geometry (2001, 8307,
sdo_point_type (-73.8042, 40.7613,null),
null, null),
'sdo_num_res=3 unit=mile', 1) = 'TRUE'
ORDER BY distance)
WHERE rownum < 4;
Practice 17-1: Managing Spatial Indexes (continued)
Oracle Spatial 11g: Essentials A - 114


6) Query the YELLOW_PAGES_PART table to find the five THAI restaurants closest to
the location (73.8042, 40.7613). Display the restaurant name and distance in miles.
Answer: Run the following query:
SELECT name, sdo_nn_distance(1) distance
FROM yellow_pages_part a
WHERE category = 1
AND sdo_nn (a.location,
sdo_geometry (2001, 8307,
sdo_point_type (-73.8042, 40.7613,null),
null, null),
'SDO_BATCH_SIZE=10 unit=mile', 1) = 'TRUE'
AND name like '%THAI%'
AND rownum < 6
ORDER BY distance;



Using function-based spatial index
7) From the D:\labs\labs folder, run the lab_17_07.sql script. This script adds
two new columns to the GEOD_CITIES table, named CITY_LONGITUDE and
CITY_LATITUDE, and both of the NUMBER type. The script then populates the
newly added columns by pulling the longitude and latitude values out of the
LOCATION column of the GEOD_CITIES table.
Answer: To run the script, enter:
@d:\labs\labs\lab_17_07.sql
8) Create the GET_GEOM function, which takes as input arguments a longitude and
latitude, and returns an SDO_GEOMETRY constructor with the SDO_POINT field
populated.
Answer: The following script creates a function that returns an SDO_GEOMETRY object.
CREATE OR REPLACE FUNCTION get_geom (longitude IN NUMBER,
latitude IN NUMBER)
RETURN sdo_geometry DETERMINISTIC is
BEGIN
RETURN sdo_geometry (2001, 8307,
sdo_point_type (longitude,
Practice 17-1: Managing Spatial Indexes (continued)
Oracle Spatial 11g: Essentials A - 115
latitude,
NULL),
NULL, NULL);
END;
/
9) Insert a row into USER_SDO_GEOM_METADATA for the GET_GEOM function-based
spatial index.
Answer: To insert the metadata, run the following INSERT statement:
INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME,
DIMINFO, SRID)
VALUES ('GEOD_CITIES',
'STUDENT.GET_GEOM(CITY_LONGITUDE,CITY_LATITUDE)',
SDO_DIM_ARRAY
(SDO_DIM_ELEMENT('LONG', -180.0, 180.0, 0.05),
SDO_DIM_ELEMENT('LAT', -90.0, 90.0, 0.05)
),
8307);
COMMIT;
10) Create a function-based spatial index for the CITY_LONGITUDE and
CITY_LATITUDE columns in the GEOD_CITIES table.
Answer: Run the following statements to create a function-based spatial index:
CREATE INDEX geod_cities_fbsidx
ON geod_cities(get_geom(CITY_LONGITUDE,CITY_LATITUDE))
indextype is mdsys.spatial_index;
11) Use the function-based spatial index on the CITY_LONGITUDE and
CITY_LATITUDE columns of GEOD_CITIES to find all cities within 100 miles of
(73.94, 40.66).
Answer: Run the following query:
SELECT /*+ ordered */ a.city
FROM geod_cities a
WHERE SDO_WITHIN_DISTANCE (STUDENT.GET_GEOM(a.city_longitude,
a.city_latitude),
sdo_geometry (2001, 8307,
sdo_point_type (-73.94, 40.66,
null),
null, null),
'distance=100 unit=mile') = 'TRUE';
Practice 17-1: Managing Spatial Indexes (continued)
Oracle Spatial 11g: Essentials A - 116



Importing the ADCI Transportable Tablespace
12) Import the adci transportable tablespace. Note the following important points
before beginning the import:
i) Log in using system/oracle as the username/password. You create an
adci user identified by the adci password. Grant required privileges to the
user.
ii) You must also create a new directory object named adci_dumpdir
pointing to the D:\labs\data folder.
iii) The adci_data.dmp and adci_data.dbf files are available in the
D:\labs\data folder.
Note: The data imported from this transportable tablespace file will be used in the
lessons titled Geocoding Address Data and Using the Spatial Routing Engine.

Answer: Perform the following step to successfully import the transportable tablespace
file:
a) Log in using system/oracle as the username and password. First, create the
Data Pump directory by using the following command:
conn system/oracle
CREATE DIRECTORY adci_dumpdir AS 'd:\labs\data';
b) To create a new user adci with the required privileges, run the following
statement:
grant connect, resource TO adci IDENTIFIED BY adci;
c) Now, open a command window to import the tablespace:
impdp system/oracle directory=adci_dumpdir
dumpfile=adci_data.dmp
transport_datafiles='d:\labs\data\adci_data.dbf'
Practice 17-1: Managing Spatial Indexes (continued)
Oracle Spatial 11g: Essentials A - 117



13) Assuming that you are still connected using system/oracle as the
username/password, alter the newly imported tablespace, adci_data to have read/
write access.
Answer: Run the following statement:

ALTER TABLESPACE adci_data READ WRITE;
14) Alter the adci user to have unlimited quota on the adci_data tablespace.
Answer: Run the following statement:

ALTER USER adci QUOTA UNLIMITED ON adci_data;
15) Connect using adci/adci as the username and password. Initialize the indexes for
the transportable tablespace.
Answer: Run the following statement:
EXECUTE SDO_UTIL.INITIALIZE_INDEXES_FOR_TTS;




Practice 17-1: Managing Spatial Indexes (continued)
Oracle Spatial 11g: Essentials A - 118
16) There are some mapping styles, themes, and maps for the sample mapping data
provided by ADCI. Insert all the records from the SDO_MAPS, SDO_THEMES, and
SDO_STYLES tables into the USER_SDO_MAPS, USER_SDO_THEMES, and
USER_SDO_STYLES tables respectively.
Answer: Run the following INSERT statements:
INSERT INTO USER_SDO_MAPS SELECT * FROM SDO_MAPS;
INSERT INTO USER_SDO_THEMES SELECT * FROM SDO_THEMES;
INSERT INTO USER_SDO_STYLES SELECT * FROM SDO_STYLES;
commit;



The transported sample data is ready to use. You use the data in the forthcoming practices
for lessons 18 and 19.



Oracle Spatial 11g: Essentials A - 119
Practices for Lesson 18
In this practice, you work on the ADCI sample data set that you imported through the
transportable tablespace file. You run geocode queries in this practice. You also create a
trigger to automatically geocode address data. Finally, you go through the steps of
deploying and using the geocoder servlet.

Prerequisite: To perform this practice completely, you must have completed the practice
for lesson 7.
If you did not, go back to Practice 7-1 and perform all the steps to set up MapViewer.

For this practice, you must have also completed the last section, Importing the ADCI
Transportable Tablespace, of Practice 17-1. If you did not, perform the following steps.
i) In SQL*Plus, run the followed script:
@d:\labs\catchup_scripts\create_adci.sql
ii) In Windows Explorer, double-click the import_adci.bat file to run it.
iii) Again in SQL*Plus, run the following script:
@d:\labs\catchup_scripts\initialize_adci.sql



Oracle Spatial 11g: Essentials A - 120
Practice 18-1: Geocoding Address Data
1) Connect using adci/adci as the username/password. Geocode the following
address with DEFAULT match mode:
i) 'Thomas Jefferson ST', 'Washington, DC 20007'
Answer: Run the following queries to geocode the preceding address:
SELECT SDO_gcdr.geocode('ADCI',
SDO_keywordArray('Thomas Jefferson ST', 'Washington, DC
20007'), 'US', 'DEFAULT')
FROM DUAL ;


2) Geocode the following address with EXACT match mode:
i) 'Thomas Jefferson ST', 'Washington, DC 20007'
Answer: Run the following queries:
SELECT SDO_gcdr.geocode('ADCI',
SDO_keywordArray('Thomas Jefferson ST', 'Washington, DC
20007'), 'US', 'EXACT')
FROM DUAL ;


3) Grant the SELECT privilege on the following tables to the student user:
i) GC_AREA_US
ii) GC_COUNTRY_PROFILE
iii) GC_COUNTRY_PROFILE_US
iv) GC_INTERSECTION_US
v) GC_PARSER_PROFILEAFS
vi) GC_PARSER_PROFILES
vii) GC_POI_US
viii) GC_POSTAL_CODE_US
ix) GC_ROAD_SEGMENT_US
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 121
x) GC_ROAD_US
Answer: To grant privileges, run the following statements:
grant select on GC_AREA_US to student;
grant select on GC_COUNTRY_PROFILE to student;
grant select on GC_COUNTRY_PROFILE_US to student;
grant select on GC_INTERSECTION_US to student;
grant select on GC_PARSER_PROFILEAFS to student;
grant select on GC_PARSER_PROFILES to student;
grant select on GC_POI_US to student;
grant select on GC_POSTAL_CODE_US to student;
grant select on GC_ROAD_SEGMENT_US to student;
grant select on GC_ROAD_US to student;
4) Log in using student/student as the username and password. A trigger can be
created to automatically geocode address data as it is being inserted into a table.
Create a table called CUSTOMERS with the following columns:
i) id number
ii) address varchar2(30)
iii) city varchar2(30)
iv) state char(2)
v) zip char(5)
vi) location sdo_geometry
Answer: Run the following statement to create the CUSTOMERS table:
conn student/student
CREATE TABLE customers (
id number,
address varchar2(30),
city varchar2(30),
state char(2),
zip char(5),
location sdo_geometry);
5) Create a trigger on the CUSTOMERS table so that whenever a new row is inserted, or
an update happens, a geocoding request is executed to update the location field of the
CUSTOMERS table.
Answer: To create a trigger, enter the following code:
CREATE OR REPLACE TRIGGER GEOCODE_CUSTOMER
BEFORE INSERT OR UPDATE OF ADDRESS, CITY, STATE, ZIP ON
CUSTOMERS
FOR EACH ROW
BEGIN
:NEW.LOCATION := SDO_GCDR.GEOCODE_AS_GEOMETRY(
'ADCI',
sdo_keywordarray(:new.address,
:new.city||', '||
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 122
:new.state||' '||
:new.zip),
'US');
END;
/

6) Insert the following address data into the CUSTOMERS table. Commit the data.
i) 1, '1052 Thomas Jefferson St', 'Washington, DC
20007'
Answer: To insert rows in the CUSTOMERS table, execute the following statements:
INSERT INTO customers (id, address, city, state, zip) values (
1,
'1052 Thomas Jefferson St',
'Washington',
'DC',
20007);

commit;
7) Select the location column data from the CUSTOMERS table. Note that the
location column has SDO_GEOMETRY data, which was not included when the
data was inserted.
Answer: To select data from the CUSTOMERS table, run the following query:
SELECT location from customers;


8) Add an entry to the USER_SDO_GEOM_METADATA view.
Answer: To add an entry in the USER_SDO_GEOM_METADATA view, enter the
following statement:
INSERT INTO user_sdo_geom_metadata values
('CUSTOMERS','LOCATION',
SDO_DIM_ARRAY(SDO_DIM_ELEMENT('X',-180,180,0.05),
SDO_DIM_ELEMENT('Y', -90, 90,0.05)), 8307);
9) Create a spatial index, customer_sidx, on customers(location).
Answer: To create a spatial index, run the following statement:
CREATE INDEX customer_sidx on customers (location)
indextype is mdsys.spatial_index parameters
('layer_gtype=point');
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 123
Deploying and Using the Geocoder Servlet
10) Ensure that the OC4J is running. If not, run the start.bat file from the
d:\mv10131_qs folder. Deploy the geocoder servlet by using Enterprise Manager
Application Server Control.
Answer: Perform the following steps to deploy the geocoder servlet:
a) Start Internet Explorer. Enter to the following URL:
http://localhost:8888/em. Log in using oc4jadmin as the username
and welcome as the password. Click Login.


b) Click Applications. Then click Deploy.
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 124

c) Click Browse. Select the geocoder.ear file. Click Next. The archive is
uploaded to the server where Application Server Control is running.



d) Enter Geocoder in the Application Name field. Click Next.
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 125

e) Click Deploy.

Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 126
The Application Deployer for geocoder completes successfully.


f) Click Return.
11) Start the Geocoder servlet home page by using the URL: http://localhost:
8888/geocoder. From the Administration page, edit the geocoder configuration file,
geocodercfg.xml. Set the user to adci and password to adci.
Answer: Edit geocodercfg.xml as follows:
a) Open a new Internet Explorer window and enter the following URL:
http://localhost: 8888/geocoder. Click Administration.
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 127

b) In the Connect to localhost dialog box, enter oc4jadmin and welcome as the
username and password respectively. Click OK.

c) Click Modify on the Oracle Spatial Geocoder Administration page. The code
becomes editable. Change the user to adci and the password to adci as
highlighted in the following screenshot:
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 128


d) Click Save changes.
12) Restart Geocoder. Open a new geocoder servlet homepage by using the URL:
http://localhost:8888/geocoder/
Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 129
Answer: After you save the changes you made to the geocoders configuration, scroll
down on the same page and click Restart geocoder.



Open Internet Explorer and paste the URL in the address bar. The geocoder servlet home
page is as shown in the following screenshot:


Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 130
13) Click the XML geocoding request page link. Modify the geocoding request to the
following address:
i) <us_form2 street="1801 K Street NW"
city="Washington" state="DC"/>.
ii) Submit the request.
Answer: Perform the following steps:
a) Click the XML geocoding request page link.
b) Between the input address tags, paste the following address:
i) <us_form2 street="1801 K Street NW"
city="Washington" state="DC"/>
Note: If you do not want to type this, copy it from the sol_18_13.txt file.

c) Click Submit. View the result. The result is shown in the following screenshot:



Practice 18-1: Geocoding Address Data (continued)
Oracle Spatial 11g: Essentials A - 131
14) For a reverse-geocoding request, input the following longitude and latitude in
Washington DC. View the results.
i) <input_location id="27010" country="us"
longitude="-77.04207869999999" latitude="38.90265"
/>
Answer:
a) Click the Back button of Internet Explorer to go back to the request page.
b) In the Reverse Geocoding Request box, between the address_list tags, paste
the following:
i) <input_location id="27010" country="us"
longitude="-77.04207869999999" latitude="38.90265"
/>
Note: If you do not want to type this, copy it from the sol_18_14.txt file.

c) Click Submit. View the results. The result is shown in the following screenshot:

15) Exit the geocoder.
Answer: Close the Internet Explorer windows.



Oracle Spatial 11g: Essentials A - 132
Practices for Lesson 19
In this practice, you work through deploying and configuring the RouteServer, and
then send and receive a route request and response respectively. Finally, you view the
XML response.
Prerequisite: To perform this practice completely, you must have completed the
practices for lesson 7, 17(last section), and 18. If you did not, go back to Practice 7-1 and
perform all the steps to set up MapViewer.

For this practice, you must have also completed the last section, Importing the ADCI
Transportable Tablespace, of Practice 17. If you did not, then follow the instructions in
the Pre-requisite section of Practice 18.

For this practice, you must have completed the practice for lesson 18. The geocoder must
be configured (either in the database or as a servlet) before the router is configured. In the
routers web.xml file, you specify which geocoder it will use. Therefore, complete the
practice for lesson 18 before beginning with this practice.




Oracle Spatial 11g: Essentials A - 133
Practice 19-1: Using the Spatial Routing Engine
1) Ensure that the OC4J is running. If not, run the start.bat file from your
mapviewer folder. Deploy RouteServer by using Enterprise Manager Application
Server Control.
Answer: Perform the following steps to deploy the RouteServer:
a) Start Internet Explorer. Enter the following URL:
http://localhost:8888/em. Log in using oc4jadmin as the username
and welcome as the password. Click Login.


b) Click Applications. Then click Deploy.
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 134

c) Click Browse. Select the routeserver.ear file. Click Next. The archive is
uploaded to the server where Application Server Control is running.

d) Enter RouteServer in the Application Name field. Click Next.
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 135

e) Click Deploy.


The Application deployer for RouteServer completes successfully.

f) Click Return.
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 136
2) Edit the RouteServer configuration file. The file to edit is
%OC4J_HOME%\applications\routeserver\web\WEB-INF\web.xml.
i) Before making any edits, keep a copy of the original file for reference.
ii) Edit the RouteServer initialization parameters.
iii) Set the routeserver_schema_username to adci and
routeserver_schema_password to adci.
Note: In the classroom setup, the OC4J_HOME is
d:\mv10131_qs\oc4j\j2ee\home.
Answer: Perform the following steps:
a) First, take a copy of the web.xml file before making any changes:
Copy d:\mv10131_qs\oc4j\j2ee\home\applications\routeserver\web
\WEB-INF\web.xml
d:\mv10131_qs\oc4j\j2ee\home\applications\routeserver\web
\WEB-INF\web.xml.save
b) Set the RouteServer initialization parameters, as follows:
Note: Open the file in WordPad for formatted display. Change HOST, PORT and SID
as shown in the following screenshot:
After the following comment in the file:
-- <!-- RouteServer initialization parameters -->
-- Set the value for the following parameters:

<init-param>
<param-name>routeserver_schema_jdbc_connect_string
</param-name>
<param-value>
jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)
(PORT=1521)))(CONNECT_DATA=(SID=orcl)))
</param-value>
</init-param>



c) Set routeserver_schema_username to adci and
routeserver_schema_ password to adci.
<init-param>
<param-name>routeserver_schema_username</param-name>
<param-value>adci</param-value>
</init-param>

<init-param>
<param-name>routeserver_schema_password</param-name>
<param-value>adci</param-value>
</init-param>
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 137
3) In the configuration file, there are two options for the geocoder:
httpclient: The router uses a geocoder that was deployed as a servlet.
thinclient: The router uses the geocoder in the database.
i) Set the geocoder servlet parameters in the configuration file. These parameters
are used if geocoder_type is httpclient.
Note: Because you have already set up the geocoder as a servlet, use the servlet
version. Observe that the configuration file is set up to use httpclient by default.

Answer:
a) Note that geocoder_type is already set to httpclient.

<!-- Geocoder parameters -->
<init-param>
<param-name>geocoder_type</param-name>
<param-value>httpclient</param-value>
<!--
<description>
httpclient - interacts with geocoder Java Servlet
thinclient - interacts with geocoder in Oracle Database
none - no geocoder provided
</description>
-->
</init-param>
b) Set the geocoder servlet parameters in the configuration file as follows:
<init-param>
<param-name>geocoder_http_url</param-name>
<param-value>http://localhost:8888/geocoder/gcserver
</param-value>
</init-param>
4) Set the RouteServer logging parameters in the configuration file.
Answer: To set logging parameters, see the following code:
<init-param>
<param-name>log_filename</param-name>
<param-value>
d:\mv10131_qs\oc4j\j2ee\home\log\RouteServer.log
</param-value>
<!--
<description>
Path to a file in which to write log entries
</description>
-->
</init-param>
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 138
Note: Save the file.
5) Restart OC4J by running the start.bat file. Open the RouteServer servlet
home page.
Answer:
a) If OC4J is already running in any command window, close the window to
shutdown OC4J. Navigate to d:\mv10131_qs and double-click start.bat
to start OC4J again.
b) Connect to the RouteServer Welcome page by using Internet Explorer:
http://localhost:8888/routeserver


6) Submit route requests by using nongeocoded addresses.
i) Set <start_location> as:
<us_form1 street="1801 k street nw"
lastline="washington, dc" />
ii) Set <end_location> as:
<us_form1 street="1400 pennsylvania ave nw"
lastline="washington, dc" />
Note: Try changing some of the parameters in the XML route request. Note how
the results change.
Answer:
a) On the home page, click Route Requests using un-geocoded addresses.
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 139
b) Modify <start_location> as:
<us_form1 street="1801 k street nw"
lastline="washington, dc" />
c) Modify <end_location> as:
<us_form1 street="1400 pennsylvania ave nw"
lastline="washington, dc" />
Note: If you do not want to type this, copy it from the sol_19_06.txt file.
d) Click Submit. View the results.


7) Submit route requests by using the latitude and longitude. Get the response in
Spanish.
i) For start location, enter:
(1) longitude="-77.0420786999917"
(2) latitude="38.90265"
ii) For end location, enter:
(1) longitude="-77.03197701238366"
(2) latitude="38.89552962194703"
Answer: Perform the following steps:
a) Click Route Requests using Latitude and Longitude.
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 140

b) Set the language attribute to spanish as shown in the screenshot. Modify the
latitude and longitude information for both start and end locations as follows:
<start_location>
<input_location id="1" longitude="-77.0420786999917"
latitude="38.90265" />
</start_location>

<end_location>
<input_location id="2" longitude="-77.03197701238366"
latitude="38.89552962194703" />
</end_location>
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 141
Note: If you do not want to type this, copy it from the sol_19_07.txt file.


c) Click Submit. View the results. The directions are generated in Spanish.
Practice 19-1: Using the Spatial Routing Engine (continued)
Oracle Spatial 11g: Essentials A - 142