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.

Computing Cardinal Directions to nearby geometries

Sunday March 03 2013 at 22:46

Keywordscardinal direction geometry objects

This article shows how to compute a cardinal direction from one land parcel to another.

I was asked the other day if I could help derive the direction from a selected land parcel to its neighbouring parcels (request slightly modified):

Below is a screenshot showing an example of what I mean. I need to get the directions of parcel no (12) , it should give me (15) as north, (14) as south, (1,8) as west.


I have chosen to implement the direction from one point to another in a generic function that can accept and process geodetic (long/lat) data and planar data. The function does not determine if a supplied SDO_GEOMETRY p_start_point’s sdo_srid is geodetic or not (this can, however, be done easily), rather it exposes a parameter called p_projected which the user must set to 1 (or any positive number) if the SDO_SRID is planar and 0 if geodetic (eg 8307). Failure to set the right value will generate strange results.

In addition, the created function computes a bearing from p_start_point to p_end_point and then turns this into one of 16 cardinal directions based on the compass rose. If you only need the 4 main points, modify the function accordingly.

  2. FUNCTION CardinalDirection(p_start_point IN sdo_geometry,
  3.                            p_end_point   IN sdo_geometry,
  4.                            p_tolerance   IN NUMBER DEFAULT 0.05,
  5.                            p_projected   IN INTEGER DEFAULT 1)
  6. RETURN varchar2 deterministic
  7. AS
  8.   c_PI CONSTANT NUMBER := acos(-1);
  9.   v_bearing NUMBER;
  10.   v_tilt    NUMBER;
  11.   v_vertex1 mdsys.vertex_type;
  12.   v_vertex2 mdsys.vertex_type;
  13.   FUNCTION ST_Azimuth(p_dE1 IN NUMBER, p_dN1 IN NUMBER,
  14.                       p_dE2 IN NUMBER, p_dN2 IN NUMBER)
  16.   IS
  17.       dBearing NUMBER;
  18.       dEast    NUMBER;
  19.       dNorth   NUMBER;
  20.   BEGIN
  21.       IF (p_dE1 IS NULL OR p_dN1 IS NULL OR
  22.           p_dE2 IS NULL OR p_dE2 IS NULL ) THEN
  23.          RETURN NULL;
  24.       END IF;
  25.       IF ( (p_dE1 = p_dE2) AND (p_dN1 = p_dN2) ) THEN
  26.          RETURN NULL;
  27.       END IF;
  28.       dEast  := p_dE2 - p_dE1;
  29.       dNorth := p_dN2 - p_dN1;
  30.       IF ( dEast = 0 ) THEN
  31.           dBearing := CASE WHEN ( dNorth < 0 )
  32.                            THEN c_PI
  33.                            ELSE 0
  34.                        END;
  35.       ELSE
  36.           dBearing := -aTan(dNorth / dEast) + c_PI / 2;
  37.       END IF;
  38.       RETURN CASE WHEN ( dEast < 0 )
  39.                   THEN dBearing + c_PI
  40.                   ELSE dBearing
  41.               END;
  42.   END ST_Azimuth;
  43. BEGIN
  44.   IF (p_start_point IS NULL OR p_end_point IS NULL) THEN
  45.      RETURN NULL;
  46.   END IF;
  47.   -- If Geodetic....
  48.   IF (NVL(ABS(p_projected),1) = 0 ) THEN
  50.              p_start_point,
  51.              p_end_point,
  52.              p_tolerance,v_bearing,v_tilt);
  53.   ELSE
  54.     v_vertex1 := sdo_util.getVertices(p_start_point)(1);
  55.     v_vertex2 := sdo_util.getVertices(p_end_point)(1);
  56.     v_bearing := ST_Azimuth(v_vertex1.X, v_vertex1.Y,
  57.                             v_vertex2.X, v_vertex2.Y);
  58.   END IF;
  59.   v_bearing := round(v_bearing * (180.0 / acos(-1)),2);
  61.          WHEN v_bearing IS NULL THEN 'NULL'
  62.          WHEN /* Cardinal Point 0     */ v_bearing BETWEEN 348.75 AND   0.0
  63.                                       OR v_bearing BETWEEN   0.0  AND  11.25 THEN 'N'
  64.          WHEN /* Cardinal Point 22.5  */ v_bearing BETWEEN  11.25 AND  33.75 THEN 'NNE'
  65.          WHEN /* Cardinal Point 45    */ v_bearing BETWEEN  33.75 AND  56.25 THEN 'NE'
  66.          WHEN /* Cardinal Point 67.5  */ v_bearing BETWEEN  56.25 AND  78.75 THEN 'ENE'
  67.          WHEN /* Cardinal Point 90    */ v_bearing BETWEEN  78.75 AND 101.25 THEN 'E'
  68.          WHEN /* Cardinal Point 112.5 */ v_bearing BETWEEN 101.25 AND 123.75 THEN 'ESE'
  69.          WHEN /* Cardinal Point 135   */ v_bearing BETWEEN 123.75 AND 146.25 THEN 'SE'
  70.          WHEN /* Cardinal Point 157.5 */ v_bearing BETWEEN 146.25 AND 168.75 THEN 'SSE'
  71.          WHEN /* Cardinal Point 180   */ v_bearing BETWEEN 168.75 AND 191.25 THEN 'S'
  72.          WHEN /* Cardinal Point 202.5 */ v_bearing BETWEEN 191.25 AND 213.75 THEN 'SSW'
  73.          WHEN /* Cardinal Point 225   */ v_bearing BETWEEN 213.75 AND 236.25 THEN 'SW'
  74.          WHEN /* Cardinal Point 247.5 */ v_bearing BETWEEN 236.25 AND 258.75 THEN 'WSW'
  75.          WHEN /* Cardinal Point 270   */ v_bearing BETWEEN 258.75 AND 281.25 THEN 'W'
  76.          WHEN /* Cardinal Point 292.5 */ v_bearing BETWEEN 281.25 AND 303.75 THEN 'WNW'
  77.          WHEN /* Cardinal Point 315   */ v_bearing BETWEEN 303.75 AND 326.25 THEN 'NW'
  78.          WHEN /* Cardinal Point 337.5 */ v_bearing BETWEEN 326.25 AND 348.75 THEN 'NNW'
  79.          ELSE to_char(v_bearing)
  80.        END;        
  81. END CardinalDirection;
  82. /
  83. SHOW errors

To use the function, we can execute the following.

  3.   objectid INTEGER,
  4.   shape    sdo_geometry);
  5. INSERT INTO ADJOINING_PARCELS (OBJECTID,SHAPE) VALUES (1,SDO_GEOMETRY(2003,82362,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(359154.918,2892270.678,359132.697,2892276.612,359129.913,2892266.19,359125.472,2892249.561,359147.693,2892243.626,359153.37,2892264.881,359154.918,2892270.678)));
  6. INSERT INTO ADJOINING_PARCELS (OBJECTID,SHAPE) VALUES (4,SDO_GEOMETRY(2003,82362,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(359170.4,2892328.646,359148.179,2892334.581,359145.869,2892325.931,359140.438,2892305.596,359162.659,2892299.662,359164.723,2892307.391,359170.4,2892328.646)));
  7. INSERT INTO ADJOINING_PARCELS (OBJECTID,SHAPE) VALUES (8,SDO_GEOMETRY(2003,82362,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(359162.659,2892299.662,359140.438,2892305.596,359132.697,2892276.612,359154.918,2892270.678,359159.047,2892286.136,359162.659,2892299.662)));
  8. INSERT INTO ADJOINING_PARCELS (OBJECTID,SHAPE) VALUES (10,SDO_GEOMETRY(2003,82362,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(359200.35,2892320.647,359170.4,2892328.646,359164.723,2892307.391,359194.674,2892299.392,359200.35,2892320.647)));
  9. INSERT INTO ADJOINING_PARCELS (OBJECTID,SHAPE) VALUES (12,SDO_GEOMETRY(2003,82362,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(359188.997,2892278.137,359159.047,2892286.136,359154.918,2892270.678,359153.37,2892264.881,359183.32,2892256.882,359185.647,2892265.593,359188.997,2892278.137)));
  10. INSERT INTO ADJOINING_PARCELS (OBJECTID,SHAPE) VALUES (14,SDO_GEOMETRY(2003,82362,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(359183.32,2892256.882,359153.37,2892264.881,359147.693,2892243.626,359158.297,2892240.794,359167.326,2892238.382,359177.643,2892235.627,359180.063,2892244.687,359183.32,2892256.882)));
  11. INSERT INTO ADJOINING_PARCELS (OBJECTID,SHAPE) VALUES (15,SDO_GEOMETRY(2003,82362,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY(359194.674,2892299.392,359164.723,2892307.391,359162.659,2892299.662,359159.047,2892286.136,359188.997,2892278.137,359193.687,2892295.698,359194.674,2892299.392)));
  12. commit;
  13. DELETE FROM user_sdo_geom_metadata WHERE TABLE_NAME = 'ADJOINING_PARCELS';
  14. commit;
  16.      VALUES ('ADJOINING_PARCELS','SHAPE',MDSYS.SDO_DIM_ARRAY(MDSYS.SDO_DIM_ELEMENT('X',358925.345,359200.351,1),MDSYS.SDO_DIM_ELEMENT('Y',2892235.627,2892414.914,1)),82362);
  17. commit;
  20.        IndexType IS mdsys.spatial_index
  21.        Parameters('sdo_indx_dims=2,layer_gtype=POLYGON');
  22. -- Test
  23. SELECT p1.objectid,
  24.        p2.objectid,
  25.        CardinalDirection(
  26.           sdo_geom.sdo_centroid(p1.shape,0.05),
  27.           sdo_geom.sdo_centroid(p2.shape,0.05),
  28.           0.05,
  29.           1 /* Projected */) AS cardnlDirn,
  30.        sdo_geom.sdo_centroid(p2.shape,0.05) target
  32.        ADJOINING_PARCELS p2
  33.  WHERE p1.objectid = 12
  34.    AND sdo_anyinteract(p2.shape,p1.shape) = 'TRUE'
  35.    AND p2.objectid <> p1.objectid
  36.    AND sdo_geom.sdo_intersection(p1.shape,p2.shape,0.005).sdo_gtype <> 2001;
  37. -- Results
  38. --
  40. -------- -------- ----------
  41.       12        1 WSW
  42.       12        8 NW
  43.       12       14 SSW
  44.       12       15 NNE  

This results in the following visually.

I hope this is useful to someone, because my interlocutor thought so:

Thank you very much the code is working as I accepted and much more . God bless you that you are publishing your knowledge to others , you are the man!

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]

A wonderful way of thinking outside of the box and generating directional results that are simple and readable to anyone.

Jamie Keene 19 March 2013, 03:46 #

I am 100% novice to functions etc, and I found this post from a simple google search I made seeking out help for excel. Can this concept be used in excel? I need x/y to show cardinal direction when computing the difference in two coordinates.

Mndy 31 August 2016, 03:18 #


You should be able to re-write the functions (ST_Azimuth and CardinalDirection) in VB for running inside Excel.

I don’t have a copy of Excel so I can’t help you right now.

Good luck


Simon Greener 31 August 2016, 09:12 #