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.

ST_VertexN / ST_PointN - Extracting a specific point from any geometry

Sunday November 23 2014 at 17:08

KeywordsST_VertexN Alternate Algorithm Evolution

Evolution of the coding of an algorithm over time. st_vertexn as a case in point.

I have published a number of times and implementation of functions what would extract a specific point from any geometry object. These appear in my LINEAR PL/SQL package and the T_GEOMETRY object that was published as part of the PACT book I wrote with Dr Siva Ravada.

When working for a customer recently I had extracted the ST_VertexN, ST_StartVertex and ST_EndVertex functions from the source of the PACKT book for use by a process that needed to extract a point.

After having deployed it, I accidently deleted what I had done. For specific reasons I won’t go in to I could not access the original source, so I re-wrote the main ST_VertexN function from scratch. I publish that source here for no other reason than as a reflection on the way that algorithms or implementations can change.

  1.   FUNCTION ST_VertexN(p_geom   IN mdsys.sdo_geometry,
  2.                       p_vertex IN INTEGER)
  3.   RETURN mdsys.sdo_geometry
  4.   IS
  5.      c_i_invalid_vertex Constant pls_integer   := -20123;
  6.      c_s_invalid_vertex Constant VarChar2(100) := 'Vertex position (*POSN*) is invalid.';
  7.      v_vertex           pls_integer := NVL(p_vertex,-1); -- Index into coordinates array
  8.      v_vertices         mdsys.vertex_set_type;
  9.      v_num_vertices     pls_integer;
  10.      v_dims             pls_integer;
  11.   BEGIN
  12.     IF (p_geom IS NULL) THEN
  13.        NULL;
  14.     END IF;
  15.     v_dims         := p_geom.get_dims();
  16.     v_vertices     := mdsys.sdo_util.getVertices(p_geom);
  17.     v_num_vertices := v_vertices.COUNT;
  18.     -- Check / Set vertex request
  19.     --
  20.     IF ( v_vertex < 0 ) THEN
  21.       v_vertex := v_num_vertices - (ABS(v_vertex)-1);
  22.     END IF;
  23.     IF ( v_vertex = 0 OR ABS(v_vertex) > v_num_vertices ) THEN
  24.        raise_application_error(c_i_invalid_vertex,
  25.                                REPLACE(c_s_invalid_vertex,'*POSN*',to_char(v_vertex)),TRUE);
  26.     END IF;
  27.     RETURN CASE
  28.            WHEN (p_geom.sdo_point IS NOT NULL AND p_geom.sdo_ordinates IS NULL AND v_vertex IN (-1,1) )
  29.            THEN p_geom;
  30.            ELSE SDO_GEOMETRY((v_dims*1000)+1,
  31.                              p_geom.sdo_srid,
  32.                              CASE WHEN ( v_dims <= 3 )
  33.                                   THEN mdsys.sdo_point_type(v_vertices(v_vertex).x,
  34.                                                             v_vertices(v_vertex).y,
  35.                                                             CASE WHEN (v_dims=3) THEN v_vertices(v_vertex).y ELSE NULL END)
  36.                                   ELSE NULL
  37.                               END,
  38.                              CASE WHEN ( v_dims <= 3 )
  39.                                   THEN NULL
  40.                                   ELSE mdsys.sdo_elem_info_array(1,1,1)
  41.                               END,
  42.                              CASE WHEN ( v_dims <= 3 )
  43.                                   THEN NULL
  44.                                   ELSE mdsys.sdo_ordinate_array(v_vertices(v_vertex).x,v_vertices(v_vertex).y,v_vertices(v_vertex).z,v_vertices(v_vertex).w)
  45.                                END
  46.                             );
  47.   END ST_VertexN;
  48.   FUNCTION ST_StartVertex(p_geom IN mdsys.sdo_geometry)
  49.     RETURN mdsys.sdo_geometry
  50.   IS
  51.   BEGIN
  52.     RETURN ST_VertexN(p_geom,1);
  53.   END ST_StartVertex;
  54.   FUNCTION ST_EndVertex(p_geom IN mdsys.sdo_geometry)
  55.     RETURN mdsys.sdo_geometry
  56.   IS
  57.   BEGIN
  58.     RETURN ST_VertexN(p_geom,-1);
  59.   END ST_EndVertex;

The code had come from the PACT book. Now, I would not normally use the mdsys.vertex_set_type in PL/SQL. Why? Because it involves:

  1. An addition pass over the whole array;
  2. The creation of a new memory object that holds a copy of the original sdo_ordinates.

What if the person had only asked for the first point? It would be faster just to access the sdo_ordinate_array by converting vertex references to ordinate references.

I needed to get this written quickly to I decided to use the mdsys.vertex_set_type approach as it involved no conversion of the input p_vertex number to ordinates. The main saving, in the end, was that in this implementation I went straight from checking the input p_vertex value to returning the sdo_geometry where previously I had used IF statements to check if the geometry was a point, whether it was encoded in sdo_point_type or sdo_ordinates etc. This checking is done via case statements.

Actually, I think the new implementation looks fresher and cleaner and easier to debug.

Update: I had a bit of time, so I modified the ST_VertexN code so that it no longer needed mdsys.vertex_set_type processing directly against the sdo_ordinate_array. I decided to call this function ST_PointN as follows:

  2. FUNCTION ST_PointN(p_geom  IN mdsys.sdo_geometry,
  3.                    p_Point IN INTEGER)
  4.   RETURN mdsys.sdo_geometry
  5.   IS
  6.      c_i_invalid_Point Constant pls_integer   := -20123;
  7.      c_s_invalid_Point Constant VarChar2(100) := 'Point position (*POSN*) is invalid.';
  8.      v_Point           pls_integer := NVL(p_Point,-1); -- Index into coordinates array
  9.      v_num_points      pls_integer;
  10.      v_dims            pls_integer;
  11.      v_ord             pls_integer;
  12.   BEGIN
  13.     IF (p_geom IS NULL) THEN
  14.        NULL;
  15.     END IF;
  16.     v_dims       := p_geom.get_dims();
  17.     v_num_points := CASE WHEN p_geom.sdo_ordinates IS NULL THEN 1 ELSE p_geom.sdo_ordinates.COUNT / v_dims  END;
  18.     -- Check / Set Point request
  19.     --
  20.     IF ( v_Point < 0 ) THEN
  21.       v_Point := v_num_points - (ABS(v_Point)-1);
  22.     END IF;
  23.     IF ( v_Point = 0 OR ABS(v_Point) > v_num_points ) THEN
  24.        raise_application_error(c_i_invalid_Point,
  25.                                REPLACE(c_s_invalid_Point,'*POSN*',to_char(v_Point)),TRUE);
  26.     END IF;
  27.     v_ord := ( v_point - 1 ) * v_dims + 1;
  28.     RETURN CASE
  29.            WHEN (p_geom.sdo_point IS NOT NULL AND p_geom.sdo_ordinates IS NULL AND v_Point IN (-1,1) )
  30.            THEN p_geom
  31.            ELSE SDO_GEOMETRY((v_dims*1000)+1,
  32.                              p_geom.sdo_srid,
  33.                              CASE WHEN ( v_dims <= 3 )
  34.                                   THEN mdsys.sdo_point_type(p_geom.SDO_ORDINATES(v_ord),
  35.                                                             p_geom.SDO_ORDINATES(v_ord+1),
  36.                                                             CASE WHEN (v_dims=3)
  37.                                                                  THEN p_geom.SDO_ORDINATES(v_ord+2)
  38.                                                                  ELSE NULL
  39.                                                               END)
  40.                                   ELSE NULL
  41.                               END,
  42.                              CASE WHEN ( v_dims <= 3 )
  43.                                   THEN NULL
  44.                                   ELSE mdsys.sdo_elem_info_array(1,1,1)
  45.                               END,
  46.                              CASE WHEN ( v_dims <= 3 )
  47.                                   THEN NULL
  48.                                   ELSE mdsys.sdo_ordinate_array(
  49.                                              p_geom.SDO_ORDINATES(v_ord),
  50.                                              p_geom.SDO_ORDINATES(v_ord+1),
  51.                                              p_geom.SDO_ORDINATES(v_ord+2),
  52.                                              p_geom.SDO_ORDINATES(v_ord+3))
  53.                                END
  54.                             )
  55.       END;
  56.   END ST_PointN;
  57. /
  58. SHOW errors
  59. -- Now create start point wrapper
  60. --
  62. FUNCTION ST_StartPoint(p_geom IN mdsys.sdo_geometry)
  63.     RETURN mdsys.sdo_geometry
  64.   IS
  65.   BEGIN
  66.     RETURN ST_PointN(p_geom,1);
  67.   END ST_StartPoint;
  68. /
  69. SHOW errors
  70. -- now create end point wrapper
  71. --
  73.   FUNCTION ST_EndPoint(p_geom IN mdsys.sdo_geometry)
  74.     RETURN mdsys.sdo_geometry
  75.   IS
  76.   BEGIN
  77.     RETURN ST_PointN(p_geom,-1);
  78.   END ST_EndPoint;
  79. /
  80. SHOW errors

Some tests.

  1. WITH geom AS (
  3.            SDO_ORDINATE_ARRAY(59.8833333, 25.8666667,
  4.                               59.975, 26.1116667,
  5.                               60.1333333, 26.55,
  6.                               60.205, 27.3,
  7.                               60.2166667, 27.4666667,
  8.                               60.5494444, 27.8016667,
  9.                               60.555, 27.8369444))
  10.       AS line
  11.   FROM dual
  12. )
  13. SELECT st_startPoint(line) AS point FROM geom UNION ALL
  14. SELECT st_endPoint(line)   AS point FROM geom;
  15. --
  16. POINT
  17. ----------------------------------------------------------------------------
  18. SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(59.8833333,25.8666667,NULL),NULL,NULL)
  19. SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(60.555,27.8369444,NULL),NULL,NULL)
  20. --
  21. --  
  22. WITH geom AS (
  24.            SDO_ORDINATE_ARRAY(59.8833333, 25.8666667,
  25.                               59.975, 26.1116667,
  26.                               60.1333333, 26.55,
  27.                               60.205, 27.3,
  28.                               60.2166667, 27.4666667,
  29.                               60.5494444, 27.8016667,
  30.                               60.555, 27.8369444))
  31.       AS line
  32.   FROM dual
  33. )
  34. SELECT level AS pointN,
  35.        st_PointN(line,level) AS point
  36.   FROM geom a
  37.   CONNECT BY level <= sdo_util.getNumVertices(a.line);
  38. --
  39. --
  41. ------ ---------------------------------------------------------------------------
  42.      1 SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(59.8833333,25.8666667,NULL),NULL,NULL)
  43.      2 SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(59.975,26.1116667,NULL),NULL,NULL)
  44.      3 SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(60.1333333,26.55,NULL),NULL,NULL)
  45.      4 SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(60.205,27.3,NULL),NULL,NULL)
  46.      5 SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(60.2166667,27.4666667,NULL),NULL,NULL)
  47.      6 SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(60.5494444,27.8016667,NULL),NULL,NULL)
  48.      7 SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(60.555,27.8369444,NULL),NULL,NULL)
  49. --
  50.  7 ROWS selected
  51. --
  52. --
  53. WITH geom AS (
  54. SELECT SDO_GEOMETRY(2001, 8307, sdo_point_type(59.8833333, 25.8666667, NULL),NULL,NULL) AS  point
  55.   FROM dual
  56. )
  57. SELECT st_startPoint(point) AS sp,
  58.        st_endPoint(point)   AS ep
  59.   FROM geom ;
  60. --
  61. POINT
  62. ----------------------------------------------------------------------------
  63. SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(59.8833333,25.8666667,NULL),NULL,NULL)
  64. SDO_GEOMETRY(2001,8307,SDO_POINT_TYPE(59.8833333,25.8666667,NULL),NULL,NULL)

I hope this is useful to someone out there.

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 [3]

Dear Simon,

I need to extract the first and last coordinate of a given entity (line or area).

I’ve tested this sql code, both for all the vertices and for the first vertice, for the table ARAMAL (line entity) and it works well.

- List all the vertices

- List the first vertex
SELECT A.IPID, t.X, t.Y, t.Z, t.id FROM ARAMAL A, TABLE) t where t.id=1 ORDER BY A.IPID;

How can I obtain the last vertex with sql?

I guess your really nice functions (ST_PointN | ST_StartPoint | ST_EndPoint) should do the trick but I’m a bit confused about its syntax, even with the examples that you’ve given.

I’m sorry to ask – I’m a newbie in this world

For the previously mentioned table ARAMAL how should I apply your functions.

Thanks in advance,
Best regards


PS. Congrats on your book – I’m trying to get it for my work. Hopefully the boss will allow it.

— Pedro · 12 April 2019, 19:03 · #

Sorry, I meant:

- List all the vertices

- List the first vertex
SELECT A.IPID, t.X, t.Y, t.Z, t.id FROM ARAMAL A, TABLE) t where t.id=1 ORDER BY A.IPID;

— Pedro · 12 April 2019, 19:08 · #

I’ve written a blog article that shows you how to access the last vertex of an sdo_geometry object using Oracle’s ST_Geometry type hierarchy. “Here is the link”:


— Simon Greener · 13 April 2019, 17:06 · #