Go to content Go to navigation and search


Current Oracle Spatial Blog Articles

    Using Oracle's ST_GEOMETRY type hierarchy with SDO_GEOMETRY: ST_PointN and ST_NumPoints
    Making Sdo Geometry Metadata
    SC4O Test log
    The Frontage Problem: Creating references from land parcel street frontage boundary to point in street
    Scheduling the Export of Spatial Data in Oracle to a Shapefile each night
    Oracle CENTROID package update
    Book: "Applying And Extending Oracle Spatial"
    Create Polygons and Linestrings From Bearings And Distances (COGO)
    Simple Implementation Of Travelling Salesman Problem
    ST_Densify for Object PLSQL
    PLSQL ST_AsEWKT and ST_FromWKT Functions For Oracle (any version)
    Useful Package of Wrapper Functions for Sdo_Util.AffineTransforms
    GeoRaptor 4.x Update 2 (Project has Stalled)
    Tip: Drop that Spatial Index!
    Convert Single Geometry to Multi-part Geometry in Oracle Spatial
    Optimized Rectangle to 5 Point Polygon
    Centroid Package now supports Y ordinate seeding
    Convert GeoJSON document to Sdo_Geometry objects
    Function That Returns a Compass Point From a Whole Circle Bearing
    Playing around with Centroids by using different seed values
    Simple Oracle C Sprintf or Java String.format
    Some Oriented Point Functions
    Extracting Inner Rings Changed Ordinate Ordering: A Trap For Players Who Don't Read Documentation!
    PLS-00306: wrong number or types of arguments in call to 'SDO_GEOMETRY'
    Converting Google Earth Formatted Longitude/Latitude points to decimal degrees
    Oracle Business Intelligence Warehousing and Analytics - Spatial Summit
    How far inside, is inside? Measuring actual distance.
    Noding and building a polygon from single, overlapping linestrings
    Analyzing Spatial Query Performance Improvements in Oracle Spatial and Graph 12c Through Cross-Vendor Comparison
    ST_VertexN / ST_PointN - Extracting a specific point from any geometry
    Convert Single Point stored in SDO_ORDINATES to SDO_POINT_TYPE
    Aggregate APPEND Islands and XOR polygons
    Circular Arcs in Geodetic Polygons
    Some SDO_GEOMETRY/DIMINFO handling functions
    Changing all DIMINFO sdo_tolerance values for all metadata records in one go.
    Building Polygons from Incomplete Linestrings using ST_PolygonBuilder
    Computing Cardinal Directions to nearby geometries
    Intersecting two aggregated polygon layers with SC4O
    Spatial and Oracle 12c
    Update Triggers and SDO_GEOMETRY Equality
    Duplicate Geometry data and Data Models
    CENTROID package update
    How to calculate cumulative length of a linestring
    Compute Location from known Lat/Long point using delta easting and northing in miles
    Sorting SDO_GEOMETRY data using the ORDER BY clause of a SELECT statement
    Creating linestrings from points
    Rounding Coordinates or Ordinates in SDO_GEOMETRY
    Effects of Sdo_Geometry Ordinate Precision on Performance
    Effects of Sdo_Geometry Ordinate Precision on Storage
    The Spatial filtering of geometries: The effect of tolerances on relationships
    Application of Delaunay Triangulation and Inverse Distance Weighting (IDW) in Oracle for Soils Interpolation
    Selecting all SDO_GTYPE values for all tables/sdo_geometry columns in a schema
    CENTROID package - Tips for Use
    Announcing the Spatial Companion For Oracle (SC4O)
    Filtering Rings (Oracle Spatial)
    Splitting a polygon using one or more linestrings
    isValid, isSimple, Dimension and CoordDim methods for SDO_Geometry
    Line Merging or Collecting lines together: ST_LineMerger
    ST_DeleteVertex for Oracle SDO_Geometry based on Jaspa/JTS
    3D/4D and SRID aware Conversion functions for SDO_Geometry: WKT and EWKT
    Topological vs Non-Topological Simplification/Generalization of Aggregated Area Geometies in Oracle
    Filtering very short linestrings via bitmap function index
    CENTROID For Oracle
    Gridding a sdo_geometry line/polygon object (Oracle)
    Finding centre and radius of a circular geometry
    Constraining geometry type for sdo_geometry column in a table.
    CASE Statements and SDO_GEOMETRY
    The Power of Constraints and Indexes for Spatial Constraints: stopping duplicate points
    Replacement for SDO_GEOM.RELATE - ST_Relate based on JTS
    Changing Oracle Spatial Index Parameters on existing index
    Writing Excel Spreadsheets files from within the Oracle database using Java and PL/SQL
    Writing xSV (eg csv) files from within the Oracle database using Java and PL/SQL
    A simple spike finder for Spatial/Locator
    JTS Java class compilation for 11g and above
    Random Spatial Search Procedure
    Geometry Snapping using JTS in Oracle
    Exposing JTS's MinimumBoundingCircle functionality
    Exposing JTS's Densifier functionality
    Using JTS's Comparison Functions - HausdorffSimilarityMeasure & AreaSimilarityMeasure with SDO_GEOMETRY
    Free JTS-based Area/Length Functions
    Handy way of systematically fixing polygon geometries with 13349 and other errors
    Standalone CENTROID package now available for download
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 4 Processing Geodetic data
    Configurable Buffer: JTS and Oracle
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 3
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 2
    Free Union, Intersection, Xor and Difference Functions for Oracle Locator - Part 1
    Building Lines into Polygons in Oracle Locator / Spatial
    Finding Intersection Points between Line and Polygon
    Free version of sdo_length
    Alternative to my SQL based GetNumRings function
    External Tables and SDO_Geometry data.
    layer_gtype keyword issue when indexing linear data on 11g
    String Tokenizer for Oracle
    Free Aggregate Method for Concatenating 2D Lines in Oracle Locator 10g
    Reducing 5 Vertex Polygon to Optimized Rectangle
    Square Buffer
    Converting decimal seconds to string
    Valid conversion unit values for Oracle sdo_geom.sdo_length()
    Removing Steps in Gridded Vector Data - SmoothGrid for Oracle
    Oracle Spatial DISJOINT search/filtering
    Creating SDO_Geometry from geometric data recorded in the columns of a table
    Concave Hull Geometries in Oracle 11gR2
    Projecting SDO_GEOM_METADATA DIMINFO XY ordinates
    Instantiating MDSYS.VERTEX_TYPE
    New PL/SQL Packages - Rotate oriented point
    GeoRaptor Development Team
    Fast Refreshing Materialized View Containing SDO_GEOMETRY and SDO_GEOM.SDO_AREA function
    Performance of PL/SQL Functions using SQL vs Pure Code
    Implementing the BEST VicGrid Projection in Oracle 10gR2
    ORA-13011 errors when using SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT()
    Extract Polygons from Compound Polygon
    Detecting sdo_geometries with compound (3-point Arcs) segments
    GEOMETRY_COLUMNS for Oracle Spatial
    Convert GML to SDO_Geometry in Oracle 10gR2
    Spatial Sorting of Data via Morton Key
    Swapping Ordinates in an SDO_GEOMETRY object
    New To_3D Function
    Extend (Reduce/Contract/Skrink) Function for Oracle
    Loading and Processing GPX 1.1 files using Oracle XMLDB
    Loading Spatial Data from an external CSV file in Oracle
    Calling the Oracle Spatial shapefile loader from within the Oracle database itself
    Implementing SDO_VertexUpdate/ST_VertexUpdate for Oracle
    Implementing SDO_RemovePoint/ST_RemovePoint for Oracle
    Implementing SDO_AddPoint/ST_AddPoint for Oracle
    ESRI ArcSDE Exverted and Inverted Polygons and Oracle Spatial
    Funky Fix Ordinates By Formula
    Implementing a SetPoint/ST_SetPoint function in Oracle
    Implementing an ST_SnapToGrid (PostGIS) function for Oracle Spatial
    Generating random point data
    Implementing an Affine/ST_Affine function for Oracle Spatial
    Implementing a Scale/ST_Scale function for Oracle Spatial
    Implementing a Parallel/ST_Parallel function for linestring data for Oracle Spatial
    Implementing a Rotate/ST_Rotate function for Oracle Spatial
    Limiting table list returned when connecting to Oracle Database using ODBC
    ST_Azimuth for Oracle: AKA Cogo.Bearing
    Implementing a Translate/ST_Translate/Move function for Oracle Spatial
    Elem_Info_Array Processing: An alternative to SDO_UTIL.GetNumRings and querying SDO_ELEM_INFO itself
    Minumum Bounding Rectangle (MBR) Object Type for Oracle
    How to extract elements from the result of an sdo_intersection of two polygons.
    How to restart a database after failed parameter change
    Fixing failed spatial indexes after import using data pump
    generate_series: an Oracle implementation in light of SQL Design Patterns
    Multi-Centroid Shootout
    Oracle Spatial Centroid Shootout
    On the use of ROLLUP in Oracle SELECT statements
    Surrounding Parcels
    Spatial Pipelining
    Using Oracle's SDO_NN Operator - Some examples
    Converting distances and units of measure in Oracle Locator
    Split Sdo_Geometry Linestring at a known point
    Forcing an Sdo_Geometry object to contain only points, lines or areas
    Unpacking USER_SDO_GEOM_METADATA's DIMINFO structure using SQL
    Generating multi-points from single point records in Oracle Spatial
    Object Tables of Sdo_Geometry
    Oracle Locator vs Oracle Spatial: A Reflection on Oracle Licensing of the SDO_GEOM Package
    FAST REFRESHing of Oracle Materialized Views containing Sdo_Geometry columns
    Australian MGA/AMG Zone Calculation from geographic (longitude/latitude) data
    Loading Shapefiles (SHP) into Oracle Spatial
    Oracle Spatial Mapping and Map Rendering Performance Tips
    The significance of sdo_lb/sdo_ub in USER_SDO_GEOM_METDATA: Do I need it?
    Oracle Spatial Forum - Melbourne April 2007
    Layer_GTypes for spatial indexes
    Oracle's SQL/MM Compliant Types
    Tips and Tricks



RSS / Atom

Email me


Creative Commons License
All Blog Articles, Data Models and Free Source Code by Simon Greener, The SpatialDB Advisor is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Extend (Reduce/Contract/Skrink) Function for Oracle

Tuesday July 28 2009 at 01:06

Recently I was looking at some cadastral data with a view to working out how to polygonize the linestrings. The data contains this sort of boundary understood anomaly.

Cadastral line undershoot

To be able to able to form intersections between the cadastral boundaries and the road frontage I need to be “extend” the linestrings along the direction of the line.

To do this I found that to implement this in Oracle, because there is no function to do this, I needed to write a PL/SQL function.

Before I present the function, I decided that I would make the one function capable of being able to lengthen or extend a linestring and also shorten (reduce, contract or shrink) it. Skrinking is easy: specify the extension length as a negative number (as against a positive number for extension).

I have noted that other solutions such as FME’s ExtensionFactory which allows the user to specify that the direction for extension can be computed by 1 more more vectors or segments:

The optional SEGMENTS_TO_AVERAGE clause indicates the number of segments that should be considered when computing the orientation angle for the extension feature. By default, this is set to 1, which means the orientation of the extension feature matches the orientation of just one segment in the original feature. It can be set to any number of segments, in which case the orientation will be set to the average orientation of those segments. If the number of segments is larger than the number of segments available on the feature, then the entire feature orientation is averaged and used.

However, because I allow for shrinkage of the linestring I decided not to implement a similar feature to FME (though it would not be all that difficult to do – it’s just maths).

Another restriction for the function is that I decided to only handle single linestrings (gtype of 2 and not 6). If you need such a function then simply use the Explode function in my GEOM package and concatenate the results back together when finished.

The function allows the user to extend a linestring from the beginning (START), END or BOTH ends of the linestring.

And, finally, I don’t stop you from pumping geodetic data in to the function but the result will be, technically, incorrect. I will look to modify the function at some stage so that it handles geodetic data more correctly than the averaging that occurs now.

This is also the case for linestrings with 3-point circular curve elements: neither reduction (3-point circular curve anythere in the linestring) nor extension (where the 3-point circular curve is at either end of the linestring) respect a 3-point circular curve: it treats them as simple vertex-connected elements.

Now, like most functions, the following Extend function is dependent on other functions. The first is a function that can return a vertex in a geometry given the vertex’s position as a positive (starting at the beginning of the sdo_geometry) or negative (-1 is the last vertex, -2 second last etc). This function is in my NETWORK package but here is is:

  1.   /** ----------------------------------------------------------------------------------------
  2.   * @function   : get_point
  3.   * @precis     : Returns vertex of linestring/polygon as sdo_geometry.
  4.   * @version    : 1.0
  5.   * @description: Can nominate vertex either as positive number starting
  6.   *               at 1 up to max vertices, or specify vertex from the
  7.   *               last vertex down by specifying -1 down to -max vertices
  8.   * @usage      : FUNCTION get_point( p_geom         IN SDO_GEOMETRY,
  9.   *                                   p_point_number IN NUMBER DEFAULT 1 )
  10.   *                 RETURN SDO_GEOMETRY DETERMINISTIC;
  11.   * @param      : p_geom         : Geometry
  12.   * @paramtype  : p_geom         : MDSY.SDO_GEOMETRY
  13.   * @param      : p_point_number : Vertex number between 1..(max vertices) OR
  14.   *                                -1 .. -(max vertices)
  15.   * @paramtype  : p_point_number : Integer
  16.   * @history    : Simon Greener - June 2008 - Original coding.
  17.   * @copyright  : Free for public use
  18.   **/
  19.   CREATE FUNCTION get_point (
  20.                p_geom         SDO_GEOMETRY,
  21.                p_point_number NUMBER DEFAULT 1
  22.            ) RETURN SDO_GEOMETRY
  23.   IS
  24.     v_d     NUMBER;         -- Number of dimensions in geometry
  25.     v_gtype NUMBER;         -- SDO_GTYPE of returned geometry
  26.     v_p     NUMBER;         -- Index into ordinates array
  27.     v_px    NUMBER;         -- X of extracted point
  28.     v_py    NUMBER;         -- Y of extracted point
  29.     v_pz    NUMBER;         -- Z of extracted point
  30.   BEGIN
  31.     -- Get the number of dimensions from the gtype
  32.     v_d := SUBSTR (p_geom.SDO_GTYPE, 1, 1);
  33.     -- Verify that the point exists
  34.     -- and set index in ordinates array
  35.     IF p_point_number = 0
  36.        OR ABS(p_point_number) > p_geom.SDO_ORDINATES.COUNT()/v_d THEN
  37.       RETURN NULL;
  38.     ELSIF p_point_number <= -1 THEN
  39.       v_p := ( (p_geom.SDO_ORDINATES.COUNT() / v_d) + p_point_number ) * v_d + 1;
  40.     ELSE
  41.       v_p := (p_point_number - 1) * v_d + 1;
  42.     END IF;
  43.     -- Extract the X and Y coordinates of the desired point
  44.     v_gtype := 2001;
  45.     v_px := p_geom.SDO_ORDINATES(v_p);
  46.     v_py := p_geom.SDO_ORDINATES(v_p+1);
  47.     IF v_d > 2 THEN
  48.       v_gtype := 3001;
  49.       v_pz := p_geom.SDO_ORDINATES(v_p+2);
  50.     END IF;
  51.     -- Construct and return the point
  52.     RETURN
  53.       SDO_GEOMETRY (
  54.         v_gtype,
  55.         p_geom.SDO_SRID,
  56.         SDO_POINT_TYPE (v_px, v_py, v_pz),
  57.         NULL, NULL);
  58.   END Get_Point;

Here is how to use it:

  1. SELECT get_point(a.geom,1) AS start_geom,
  2.        get_point(a.geom,-1) AS end_geom
  3.   FROM (SELECT sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)) AS geom
  4.          FROM dual) a;
  5. -- Results
  6. START_GEOM                                                 END_GEOM
  7. ---------------------------------------------------------- ----------------------------------------------------------
  9. .
  10. 1 ROWS selected

I also use my SDO_SetPoint and SDO_RemovePoint functions that I are described by the referenced blog articles.

The function uses two internal PL/SQL functions, Extension and Reduction to effect its processing. Reduction is selected when a negative “extension” distance is supplied. If a negative distance is supplied and that distance is greater than the segment being processed, the function will “prune” segments off the end of line that is being processed. Fairly obviously an reduction distance that is greater than the length of the line will be rejected.

Here is the function.

  1.  /** ----------------------------------------------------------------------------------------
  2.   * @function    : Extend
  3.   * @precis      : Shortens or increases length of single linestring by desired amount.
  4.   * @description : To extend a linestring provide a positive number. The linestring
  5.   *                will be extended by taking the bearing of the first/last vector in the linestring
  6.   *                and extending it by the desired amount. Providing START for the p_end parameter
  7.   *                will cause the linestring to be ended at its beginning only; END ensures the
  8.   *                extension occurs from the end of the linestring; BOTH ensures extension occurs at
  9.   *                both ends. Providing a negative extension value will cause the linestring to shrink
  10.   *                from either START, END or BOTH ends. If vertices are met when shrink the linestring
  11.   *                within the distance to be shrunk the vertices will be removed.
  12.   * @version     : 1.0
  13.   * @usage      : FUNCTION get_point( p_geom      in sdo_geometry,
  14.   *                                   p_extension in number,
  15.   *                                   p_tolerance in number,
  16.   *                                   p_end       in varchar2 default 'START' )
  17.   *                 RETURN SDO_GEOMETRY DETERMINISTIC;
  18.   * @param      : p_geom         : Geometry
  19.   * @paramtype  : p_geom         : MDSY.SDO_GEOMETRY
  20.   * @param      : p_extension    : The value to extend or shrink (-ve) the linestring
  21.   * @paramtype  : p_extension    : number
  22.   * @param      : p_tolerance    : Standard Oracle diminfo tolerance.
  23.   * @paramType  : p_tolerance    : Number
  24.   * @param      : p_end          : START, END or BOTH
  25.   * @paramType  : p_end          : VARCHAR
  26.   * @history    : Simon Greener - July 2009 - Original coding.
  27.   * @copyright  : Licensed under a Creative Commons Attribution-Share Alike 2.5 Australia License.
  28.   *               (http://creativecommons.org/licenses/by-sa/2.5/au/)
  29.   **/
  31. FUNCTION extend( p_geom      IN sdo_geometry,
  32.                  p_extension IN NUMBER,
  33.                  p_tolerance IN NUMBER,
  34.                  p_end       IN varchar2 DEFAULT 'START' )
  35.   RETURN sdo_geometry
  36. AS
  37.   v_geom           sdo_geometry := p_geom;
  38.   v_geom_length    NUMBER := 0;
  39.   v_x_round_factor NUMBER;
  40.   v_y_round_factor NUMBER;
  41.   v_end            varchar2(5) := UPPER(SUBSTR(p_end,1,5));
  47.   NOT_LINEAR       EXCEPTION;  
  48.   --
  49.   PROCEDURE Extension( p_end_pt_id      IN NUMBER,
  50.                        p_internal_pt_id IN NUMBER,
  51.                        p_extension      IN NUMBER)
  52.   IS
  53.     v_extend         NUMBER := p_extension;
  54.     v_end_pt         sdo_geometry;
  55.     v_internal_pt    sdo_geometry;
  56.     v_deltaX         NUMBER;
  57.     v_deltaY         NUMBER;
  58.     v_length         NUMBER;
  59.     v_new_point      Vertex_Type;
  60.   BEGIN
  61.      v_end_pt      := Get_Point(v_geom,p_end_pt_id );
  62.      v_internal_pt := Get_Point(v_geom,p_internal_pt_id);
  63.      v_deltaX      := v_end_pt.sdo_point.x - v_internal_pt.sdo_point.x;
  64.      v_deltaY      := v_end_pt.sdo_point.y - v_internal_pt.sdo_point.y;
  65.      v_length      := SDO_GEOM.SDO_DISTANCE( v_end_pt, v_internal_pt, p_tolerance );
  66.      v_new_point   := vertex_type(NULL,NULL,NULL,NULL,NULL);
  67.      v_new_point.x := ROUND(v_internal_pt.sdo_point.x + v_deltaX * ( (v_Length + p_extension) / v_Length ), v_x_round_factor);
  68.      v_new_point.y := ROUND(v_internal_pt.sdo_point.y + v_deltaY * ( (v_Length + p_extension) / v_Length ), v_y_round_factor);
  69.      v_geom        := CODESYS.GEOM.SDO_SetPoint(v_geom,
  70.                                                 v_new_point,
  71.                                                 CASE SIGN(p_end_pt_id) WHEN -1 THEN NULL ELSE 1 END  );
  72.   END Extension;
  73.   --
  74.   PROCEDURE Reduction( p_end_pt_id      IN NUMBER,
  75.                        p_internal_pt_id IN NUMBER,
  76.                        p_extension      IN NUMBER)
  77.   IS
  78.     v_extend         NUMBER := p_extension;
  79.     v_sign           NUMBER := SIGN(p_end_pt_id);
  80.     v_pt_id          NUMBER := 0;
  81.     v_end_pt         sdo_geometry;
  82.     v_internal_pt    sdo_geometry;
  83.     v_deltaX         NUMBER;
  84.     v_deltaY         NUMBER;
  85.     v_length         NUMBER;
  86.     v_new_point      Vertex_Type;
  87.   --
  88.     FUNCTION EndPoint( p_geom IN SDO_GEOMETRY )
  89.       RETURN NUMBER
  90.     IS
  91.     BEGIN
  92.       RETURN (p_geom.SDO_ORDINATES.COUNT() / TO_NUMBER(SUBSTR(p_geom.SDO_GTYPE,1,1)) );
  93.     END EndPoint;
  94.   --
  95.   BEGIN
  96.      LOOP
  97.        v_pt_id       := v_pt_id + v_sign;
  98.        v_end_pt      := Get_Point(v_geom,v_pt_id );
  99.        v_internal_pt := Get_Point(v_geom,v_pt_id + v_sign);
  100.        v_deltaX      := v_end_pt.sdo_point.x - v_internal_pt.sdo_point.x;
  101.        v_deltaY      := v_end_pt.sdo_point.y - v_internal_pt.sdo_point.y;
  102.        v_length      := sdo_geom.sdo_distance( v_end_pt, v_internal_pt, p_tolerance );
  103.        IF ( ABS(ROUND(v_extend, v_x_round_factor + 1)) >= ROUND(v_length, v_x_round_factor + 1) ) THEN
  104.          v_geom := CODESYS.GEOM.SDO_RemovePoint(v_geom,v_pt_id);
  105.          v_extend := v_length + v_extend;
  106.          v_pt_id  := v_pt_id - v_sign;
  107.        ELSE
  108.          v_new_point   := vertex_type(NULL,NULL,NULL,NULL,NULL);
  109.          v_new_point.x := ROUND(v_internal_pt.sdo_point.x + v_deltaX * ( (v_Length + v_extend) / v_Length ), v_x_round_factor);
  110.          v_new_point.y := ROUND(v_internal_pt.sdo_point.y + v_deltaY * ( (v_Length + v_extend) / v_Length ), v_y_round_factor);
  111.          v_geom        := CODESYS.GEOM.SDO_SetPoint(v_geom,
  112.                                                     v_new_point,
  113.                                                     CASE v_sign WHEN -1 THEN EndPoint(v_geom) ELSE v_pt_id END );
  114.          EXIT;
  115.        END IF;
  116.      END LOOP;
  117.   END Reduction;
  118.   --
  119. BEGIN
  120.   IF ( p_tolerance IS NULL ) THEN
  122.   END IF;
  123.   v_x_round_factor := round(log(10,(1/p_tolerance)/2));
  124.   v_y_round_factor := round(log(10,(1/p_tolerance)/2));
  125.   IF ( v_geom IS NULL ) THEN
  127.   END IF;
  128.   -- Only support simple linestrings
  129.   IF ( MOD(v_geom.sdo_gtype,10) <> 2 ) THEN
  130.     RAISE NOT_LINEAR;
  131.   END IF;
  132.   IF ( NOT v_end IN ('START','BOTH','END') ) THEN
  134.   END IF;
  135.   IF ( p_extension IS NULL OR p_extension = 0 ) THEN
  137.   END IF;
  138.   IF ( SIGN(p_extension) = -1 ) THEN
  139.     -- Is reduction distance (when BOTH) greater than actual length of string?
  140.     v_geom_length := SDO_GEOM.SDO_LENGTH(v_geom,p_tolerance);
  141.     IF ( ABS(p_extension) >= ( v_geom_length / CASE v_end WHEN 'BOTH' THEN 2.0 ELSE 1 END ) )  THEN
  143.     END IF;
  144.   END IF;
  145.   IF v_end IN ('START','BOTH') THEN
  146.     IF ( SIGN(p_extension) = 1 ) THEN
  147.       Extension(1,2,p_extension);
  148.     ELSE
  149.       Reduction(1,2,p_extension);
  150.     END IF;
  151.   END IF;
  152.   IF v_end IN ('BOTH','END') THEN
  153.     IF ( SIGN(p_extension) = 1 ) THEN
  154.       Extension(-1,-2,p_extension);
  155.     ELSE
  156.       Reduction(-1,-2, p_extension);
  157.     END IF;
  158.    END IF;
  159.   RETURN v_geom;
  160.   EXCEPTION
  162.       raise_application_error(-20001,'p_geom may not be NULL.');
  164.       raise_application_error(-20001,'p_tolerance may not be NULL.');
  166.       raise_application_error(-20001,'p_extension value must not be 0 or NULL.');
  168.       raise_application_error(-20001,'p_geom must be a single linestring.');
  170.       raise_application_error(-20001,'p_end value (' || v_end || ') must be START, BOTH or END');
  172.       raise_application_error(-20001,'Reduction of geometry of length (' || v_geom_length || ') of each end by (' || ABS(p_extension) || ') would result in zero length geometry.');
  173. END extend;


Right, now let’s throw some test data at this function to show how it performs.


  1. -- Test Shape
  2. SELECT sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)) AS geom FROM dual;
  3. -- Results
  4. GEOM
  5. -------------------------------------------------------------------------------------------
  7. .
  8. 1 ROWS selected
  9. --
  10. -- Shrink from end by 1.414 meters ...
  11. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),-1.414,0.005,'END') AS sGeom FROM dual;
  12. -- Results
  13. SGEOM
  14. ---------------------------------------------------------------------------------------
  16. .
  17. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its reduction.

  1. -- Shrink from start by 1.414 meters ...
  2. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),-1.414,0.05,'START') AS sGeom FROM dual;
  3. -- Results
  4. SGEOM
  5. ---------------------------------------------------------------------------------------
  7. .
  8. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its reduction.

  1. -- Shrink from both ends by 1.414 meters ...
  2. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),-1.414,0.05,'BOTH') AS sGeom FROM dual;
  3. -- Results
  4. SGEOM
  5. -----------------------------------------------------------------------------------
  7. .
  8. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its reduction.

  1. -- Shrink from both ends by 1.5 meters ...
  2. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),-1.5,0.05,'BOTH') AS sGeom FROM dual;
  3. -- Results
  4. SGEOM
  5. ---------------------------------------------------------------------------------------
  7. .
  8. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its reduction.

  1. -- Shrink from both ends by 2.0 meters each ...
  2. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),-2.0,0.05,'BOTH') AS sGeom FROM dual;
  3. -- Results
  4. Error report:
  5. SQL Error: ORA-20001: Reduction OF geometry OF LENGTH (3.82842712474619) OF each END BY (2) would RESULT IN zero LENGTH geometry.
  6. ORA-06512: at "CODESYS.EXTEND", line 191
  7. ORA-06512: at line 1
  8. --
  9. -- Shrink both ends by half actual length to generate 0 length linestring...
  10. SELECT extend(a.geom,-1 * sdo_geom.sdo_length(a.geom,0.05)/2,0.05,'BOTH') AS sGeom
  11.   FROM (SELECT sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)) AS geom
  12.           FROM dual ) a;
  13. -- Results
  14. Error report:
  15. SQL Error: ORA-20001: Reduction OF geometry OF LENGTH (3.82842712474619) OF each END BY (1.914213562373095) would RESULT IN zero LENGTH geometry.
  16. ORA-06512: at "CODESYS.EXTEND", line 191
  17. ORA-06512: at line 1
  18. --
  19. -- Shrink from end by 0.2 meters less than actual length of original linestring ...
  20. SELECT extend(a.geom,-1 * (sdo_geom.sdo_length(a.geom,0.05) - 0.2),0.05,'END') AS sGeom
  21.   FROM (SELECT sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)) AS geom
  22.           FROM dual ) a;
  23. -- Results
  24. SGEOM
  25. ---------------------------------------------------------------------------------------
  27. .
  28. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its reduction.

Extension Tests

Now let’s conduct some tests showing how to extend a linestring from one, or both, ends.

  1. -- Extend from end 1.414 meters ...
  2. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),1.414,0.05,'END') AS eGeom FROM dual;
  3. -- Results
  4. EGEOM
  5. -------------------------------------------------------------------------------------------
  7. .
  8. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its extension.

  1. -- Extend from starting end 1.414 meters ...
  2. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),1.414,0.05,'START') AS egeom FROM dual;
  3. -- Results
  4. EGEOM
  5. -------------------------------------------------------------------------------------------
  7. .
  8. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its extension.

  1. -- Extend from both ends 1.414 meters ...
  2. SELECT extend(sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)),1.414,0.05,'BOTH') AS eGeom FROM dual;
  3. -- Results
  4. EGEOM
  5. -------------------------------------------------------------------------------------------
  7. .
  8. 1 ROWS selected

Let’s visualise this. The green background line is the original test line. The red dotted line is the result of its extension.


Other than extending the side boundaries of the cadastral polygon in the first image, the extend function can be used for all sorts of things. One particularly useful example is its use in extending a road centreline so that it touches the boundary of a buffer generated around the same road centreline. Here is an example based on our linestring pretending to be a road centreline!

  1. CREATE TABLE rd_centreline_extended
  2. AS
  3. SELECT 1 AS id,sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)) AS geom
  4.   FROM dual
  6. SELECT 2 AS id,extend(a.geom,1.0,0.005,'BOTH') AS geom
  7.   FROM (SELECT sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)) AS geom
  8.           FROM dual) a
  10. SELECT 3 AS id,sdo_geom.sdo_buffer(b.geom,1.0,0.005) AS geom
  11.   FROM (SELECT sdo_geometry(2002,NULL,NULL,sdo_elem_info_array(1,2,1),sdo_ordinate_array(1,1,2,2,3,2,4,3)) AS geom
  12.           FROM dual) b;
  13. -- Result
  14. CREATE TABLE succeeded.

Which, when visualised, looks like this:

I hope someone finds this useful.

I will consider looking at handling geodetic data is anyone shows any interest. Similarly, if anyone wants the function to behave in a similar manner to the FME ExtensionFactory drop me a line. Or, if anyone makes these changes themselves, I would appreciate a copy!

Creative Commons License

post this at del.icio.uspost this at Diggpost this at Technoratipost this at Redditpost this at Farkpost this at Yahoo! my webpost this at Windows Livepost this at Google Bookmarkspost this to Twitter

Comment [2]

Hi Simon,

Thanks for all of your awsome material on Oracle spatial, it has been a great help to my learning.

I recently had cause to use you to_2d function and found that given a 4d point it would return a 3d point (even thought the returned gtype was 2001).

The following code fixed it for me… notextile..

  1.  IF ( V_Gtype = 1 AND P_Geom.Sdo_Ordinates IS NOT NULL ) THEN
  2.       V_2d_Geom.Sdo_Ordinates := P_Geom.Sdo_Ordinates;
  3.       IF v_dim=3 THEN
  4.       --
  5.       -- 3D geom
  6.         v_2D_Geom.Sdo_Ordinates.TRIM(1);
  7.       ELSE
  8.       --
  9.       -- 4D
  10.         v_2D_Geom.Sdo_Ordinates.TRIM(2) ;
  11.       END IF ;

Andrew Wales 22 May 2012, 21:42 #


Ahh, yes, in the case of a point that is 3D or 4D you are right.

Thanks for the fix.


Simon Greener 22 May 2012, 23:56 #