| Title: | Spherical Geometry Operators Using the S2 Geometry Library |
| Version: | 1.1.9 |
| Description: | Provides R bindings for Google's s2 library for geometric calculations on the sphere. High-performance constructors and exporters provide high compatibility with existing spatial packages, transformers construct new geometries from existing geometries, predicates provide a means to select geometries based on spatial relationships, and accessors extract information about geometries. |
| License: | Apache License (== 2.0) |
| Encoding: | UTF-8 |
| LazyData: | true |
| RoxygenNote: | 7.3.2 |
| SystemRequirements: | cmake, OpenSSL >= 1.0.1, Abseil >= 20230802.0 |
| LinkingTo: | Rcpp, wk |
| Imports: | Rcpp, wk (≥ 0.6.0) |
| Suggests: | bit64, testthat (≥ 3.0.0), vctrs |
| URL: | https://r-spatial.github.io/s2/,https://github.com/r-spatial/s2,http://s2geometry.io/ |
| BugReports: | https://github.com/r-spatial/s2/issues |
| Depends: | R (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| NeedsCompilation: | yes |
| Packaged: | 2025-05-23 14:44:45 UTC; edzer |
| Author: | Dewey Dunnington |
| Maintainer: | Edzer Pebesma <edzer.pebesma@uni-muenster.de> |
| Repository: | CRAN |
| Date/Publication: | 2025-05-23 15:50:02 UTC |
s2: Spherical Geometry Operators Using the S2 Geometry Library
Description
Provides R bindings for Google's s2 library for geometric calculations on the sphere. High-performance constructors and exporters provide high compatibility with existing spatial packages, transformers construct new geometries from existing geometries, predicates provide a means to select geometries based on spatial relationships, and accessors extract information about geometries.
Author(s)
Maintainer: Edzer Pebesmaedzer.pebesma@uni-muenster.de (ORCID)
Authors:
Dewey Dunningtondewey@fishandwhistle.net (ORCID)
Ege Rubakrubak@math.aau.dk
Other contributors:
Jeroen Oomsjeroen.ooms@stat.ucla.edu (configure script) [contributor]
Google, Inc. (Original s2geometry.io source code) [copyright holder]
See Also
Useful links:
Report bugs athttps://github.com/r-spatial/s2/issues
Create an S2 Geography Vector
Description
Geography vectors are arrays of points, lines, polygons, and/or collectionsof these. Geography vectors assume coordinates are longitude and latitudeon a perfect sphere.
Usage
as_s2_geography(x, ...)s2_geography()## S3 method for class 's2_geography'as_s2_geography(x, ...)## S3 method for class 'wk_xy'as_s2_geography(x, ...)## S3 method for class 'wk_wkb'as_s2_geography(x, ..., oriented = FALSE, check = TRUE)## S3 method for class 'WKB'as_s2_geography(x, ..., oriented = FALSE, check = TRUE)## S3 method for class 'blob'as_s2_geography(x, ..., oriented = FALSE, check = TRUE)## S3 method for class 'wk_wkt'as_s2_geography(x, ..., oriented = FALSE, check = TRUE)## S3 method for class 'character'as_s2_geography(x, ..., oriented = FALSE, check = TRUE)## S3 method for class 'logical'as_s2_geography(x, ...)## S3 method for class 's2_geography'as_wkb(x, ...)## S3 method for class 's2_geography'as_wkt(x, ...)Arguments
x | An object that can be converted to an s2_geography vector |
... | Unused |
oriented | TRUE if polygon ring directions are known to be correct(i.e., exterior rings are defined counter clockwise and interiorrings are defined clockwise). |
check | Use |
Details
The coercion functionas_s2_geography() is used to wrap the inputof most functions in the s2 package so that you can use other objects withan unambiguious interpretation as a geography vector. Geography vectorshave a minimalvctrs implementation, so you canuse these objects in tibble, dplyr, and other packages that use the vctrsframework.
Value
An object with class s2_geography
See Also
s2_geog_from_wkb(),s2_geog_from_text(),s2_geog_point(),s2_make_line(),s2_make_polygon() for other ways tocreate geography vectors, ands2_as_binary() ands2_as_text()for other ways to export them.
S2 Geography Transformations
Description
These functions operate on one or more geography vectors andreturn a geography vector.
Usage
s2_boundary(x)s2_centroid(x)s2_closest_point(x, y)s2_minimum_clearance_line_between(x, y)s2_difference(x, y, options = s2_options())s2_sym_difference(x, y, options = s2_options())s2_intersection(x, y, options = s2_options())s2_union(x, y = NULL, options = s2_options())s2_snap_to_grid(x, grid_size)s2_simplify(x, tolerance, radius = s2_earth_radius_meters())s2_rebuild(x, options = s2_options())s2_buffer_cells( x, distance, max_cells = 1000, min_level = -1, radius = s2_earth_radius_meters())s2_convex_hull(x)s2_centroid_agg(x, na.rm = FALSE)s2_coverage_union_agg(x, options = s2_options(), na.rm = FALSE)s2_rebuild_agg(x, options = s2_options(), na.rm = FALSE)s2_union_agg(x, options = s2_options(), na.rm = FALSE)s2_convex_hull_agg(x, na.rm = FALSE)s2_point_on_surface(x, na.rm = FALSE)Arguments
x,y | geography vectors. These inputsare passed to |
options | An |
grid_size | The grid size to which coordinates should be snapped;will be rounded to the nearest power of 10. |
tolerance | The minimum distance between vertexes to use whensimplifying a geography. |
radius | Radius of the earth. Defaults to the average radius ofthe earth in meters as defined by |
distance | The distance to buffer, in units of |
max_cells | The maximum number of cells to approximate a buffer. |
min_level | The minimum cell level used to approximate a buffer(1 - 30). Setting this value too high will result in unnecessarilylarge geographies, but may help improve buffers along long, narrowregions. |
na.rm | For aggregate calculations use |
Model
The geometry model indicates whether or not a geometry includes its boundaries.Boundaries of line geometries are its end points.OPEN geometries do not contain their boundary (model = "open"); CLOSEDgeometries (model = "closed") contain their boundary; SEMI-OPEN geometries(model = "semi-open") contain half of their boundaries, such that when two polygonsdo not overlap or two lines do not cross, no point exist that belong tomore than one of the geometries. (This latter form, half-closed, isnot present in the OpenGIS "simple feature access" (SFA) standard nor DE9-IM onwhich that is based). The default values fors2_contains() (open)and covers/covered_by (closed) correspond to the SFA standard specificationof these operators.
See Also
BigQuery's geography function reference:
Examples
# returns the boundary:# empty for point, endpoints of a linestring,# perimeter of a polygons2_boundary("POINT (-64 45)")s2_boundary("LINESTRING (0 0, 10 0)")s2_boundary("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")# returns the area-weighted centroid, element-wises2_centroid("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")s2_centroid("LINESTRING (0 0, 10 0)")# s2_point_on_surface guarantees a point on surface# Note: this is not the same as st_point_on_surfaces2_centroid("POLYGON ((0 0, 10 0, 1 1, 0 10, 0 0))")s2_point_on_surface("POLYGON ((0 0, 10 0, 1 1, 0 10, 0 0))")# returns the unweighted centroid of the entire inputs2_centroid_agg(c("POINT (0 0)", "POINT (10 0)"))# returns the closest point on x to ys2_closest_point( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POINT (0 90)" # north pole!)# returns the shortest possible line between x and ys2_minimum_clearance_line_between( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POINT (0 90)" # north pole!)# binary operations: difference, symmetric difference, intersection and unions2_difference( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))", # 32 bit platforms may need to set snap rounding s2_options(snap = s2_snap_level(30)))s2_sym_difference( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))", # 32 bit platforms may need to set snap rounding s2_options(snap = s2_snap_level(30)))s2_intersection( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))", # 32 bit platforms may need to set snap rounding s2_options(snap = s2_snap_level(30)))s2_union( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))", # 32 bit platforms may need to set snap rounding s2_options(snap = s2_snap_level(30)))# s2_convex_hull_agg builds the convex hull of a list of geometriess2_convex_hull_agg( c( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))" ))# use s2_union_agg() to aggregate geographies in a vectors2_coverage_union_agg( c( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POLYGON ((5 5, 15 5, 15 15, 5 15, 5 5))" ), # 32 bit platforms may need to set snap rounding s2_options(snap = s2_snap_level(30)))# snap to grid rounds coordinates to a specified grid sizes2_snap_to_grid("POINT (0.333333333333 0.666666666666)", 1e-2)Compute feature-wise and aggregate bounds
Description
s2_bounds_rect() returns a bounding latitude-longituderectangle that contains the region;s2_bounds_cap() returns a bounding circlerepresented by a centre point (lat, lng) and an angle. The bound may not be tightfor points, polylines and geometry collections. The rectangle returned may depend onthe order of points or polylines.lng_lo values larger thanlng_hi indicateregions that span the antimeridian, see the Fiji example.
Usage
s2_bounds_cap(x)s2_bounds_rect(x)Arguments
x | An |
Value
Both functions return adata.frame:
s2_bounds_rect(): Columnsminlng,minlat,maxlng,maxlat(degrees)s2_bounds_cap(): Columnslng,lat,angle(degrees)
Examples
s2_bounds_cap(s2_data_countries("Antarctica"))s2_bounds_cap(s2_data_countries("Netherlands"))s2_bounds_cap(s2_data_countries("Fiji"))s2_bounds_rect(s2_data_countries("Antarctica"))s2_bounds_rect(s2_data_countries("Netherlands"))s2_bounds_rect(s2_data_countries("Fiji"))Create S2 Cell vectors
Description
The S2 cell indexing system forms the basis for spatial indexingin the S2 library. On their own, S2 cells can represent pointsor areas. As a union, a vector of S2 cells can approximate aline or polygon. These functions allow direct access to theS2 cell indexing system and are designed to have minimal overheadsuch that looping and recursion have acceptable performancewhen used within R code.
Usage
s2_cell(x = character())s2_cell_sentinel()s2_cell_invalid()as_s2_cell(x, ...)## S3 method for class 's2_cell'as_s2_cell(x, ...)## S3 method for class 'character'as_s2_cell(x, ...)## S3 method for class 's2_geography'as_s2_cell(x, ...)## S3 method for class 'wk_xy'as_s2_cell(x, ...)## S3 method for class 'integer64'as_s2_cell(x, ...)new_s2_cell(x)Arguments
x | The canonical S2 cell identifier as a character vector. |
... | Passed to methods |
Details
Under the hood, S2 cell vectors are represented in R as vectorsof typedouble(). This works because S2 cell identifiers are64 bits wide, as aredoubles on all systems where R runs (Thesame trick is used by the bit64 package to represent signed64-bit integers). As a happy accident,NA_real_ is not a validor meaningful cell identifier, so missing value support in theway R users might expect is preserved. It is worth noting thatthe underlying value ofs2_cell_sentinel() would normally beconsideredNA; however, as it is meaningful and useful whenprogramming with S2 cells, customis.na() and comparison methodsare implemented such thats2_cell_sentinel() is greater thanall valid S2 cells and not considered missing. Users can and shouldimplement compiled code that uses the underlying bytes of thevector, ensuring that the class of any returned object that shouldbe interpreted in this way is constructed withnew_s2_cell().
Value
An object of class s2_cell
Examples
s2_cell("4b59a0cd83b5de49")as_s2_cell(s2_lnglat(-64, 45))as_s2_cell(s2_data_cities("Ottawa"))S2 cell operators
Description
S2 cell operators
Usage
s2_cell_is_valid(x)s2_cell_debug_string(x)s2_cell_to_lnglat(x)s2_cell_center(x)s2_cell_boundary(x)s2_cell_polygon(x)s2_cell_vertex(x, k)s2_cell_level(x)s2_cell_is_leaf(x)s2_cell_is_face(x)s2_cell_area(x, radius = s2_earth_radius_meters())s2_cell_area_approx(x, radius = s2_earth_radius_meters())s2_cell_parent(x, level = -1L)s2_cell_child(x, k)s2_cell_edge_neighbour(x, k)s2_cell_contains(x, y)s2_cell_distance(x, y, radius = s2_earth_radius_meters())s2_cell_max_distance(x, y, radius = s2_earth_radius_meters())s2_cell_may_intersect(x, y)s2_cell_common_ancestor_level(x, y)s2_cell_common_ancestor_level_agg(x, na.rm = FALSE)Arguments
x,y | An |
k | An integer between 0 and 3 |
radius | The radius to use (e.g., |
level | An integer between 0 and 30, inclusive. |
na.rm | Remove NAs prior to computing aggregate? |
Create S2 Cell Union vectors
Description
Create S2 Cell Union vectors
Usage
s2_cell_union(x = list())## S3 method for class 's2_cell_union'as_s2_geography(x, ...)as_s2_cell_union(x, ...)## S3 method for class 's2_cell_union'as_s2_cell_union(x, ...)## S3 method for class 's2_cell'as_s2_cell_union(x, ...)## S3 method for class 'character'as_s2_cell_union(x, ...)Arguments
x | A |
... | Passed to S3 methods |
Value
An object of class "s2_cell_union".
S2 cell union operators
Description
S2 cell union operators
Usage
s2_cell_union_normalize(x)s2_cell_union_contains(x, y)s2_cell_union_intersects(x, y)s2_cell_union_intersection(x, y)s2_cell_union_union(x, y)s2_cell_union_difference(x, y)s2_covering_cell_ids( x, min_level = 0, max_level = 30, max_cells = 8, buffer = 0, interior = FALSE, radius = s2_earth_radius_meters())s2_covering_cell_ids_agg( x, min_level = 0, max_level = 30, max_cells = 8, buffer = 0, interior = FALSE, radius = s2_earth_radius_meters(), na.rm = FALSE)Arguments
x,y | |
min_level,max_level | The minimum and maximum levels to constrain thecovering. |
max_cells | The maximum number of cells in the covering. Defaults to8. |
buffer | A distance to buffer outside the geography |
interior | Use |
radius | The radius to use (e.g., |
na.rm | Remove NAs prior to computing aggregate? |
Matrix Functions
Description
These functions are similar to accessors and predicates, but instead ofrecyclingx andy to a common length and returning a vector of thatlength, these functions return a vector of lengthx with each elementi containing information about how the entire vectory relates tothe feature atx[i].
Usage
s2_closest_feature(x, y)s2_closest_edges( x, y, k, min_distance = -1, max_distance = Inf, radius = s2_earth_radius_meters())s2_farthest_feature(x, y)s2_distance_matrix(x, y, radius = s2_earth_radius_meters())s2_max_distance_matrix(x, y, radius = s2_earth_radius_meters())s2_contains_matrix(x, y, options = s2_options(model = "open"))s2_within_matrix(x, y, options = s2_options(model = "open"))s2_covers_matrix(x, y, options = s2_options(model = "closed"))s2_covered_by_matrix(x, y, options = s2_options(model = "closed"))s2_intersects_matrix(x, y, options = s2_options())s2_disjoint_matrix(x, y, options = s2_options())s2_equals_matrix(x, y, options = s2_options())s2_touches_matrix(x, y, options = s2_options())s2_dwithin_matrix(x, y, distance, radius = s2_earth_radius_meters())s2_may_intersect_matrix(x, y, max_edges_per_cell = 50, max_feature_cells = 4)Arguments
x,y | Geography vectors, coerced using |
k | The number of closest edges to consider when searching. Notethat in S2 a point is also considered an edge. |
min_distance | The minimum distance to consider when searching foredges. This filter is applied after the search is complete (i.e.,may cause fewer than |
max_distance | The maximum distance to consider when searching foredges. This filter is applied before the search. |
radius | Radius of the earth. Defaults to the average radius ofthe earth in meters as defined by |
options | An |
distance | A distance on the surface of the earth in the same unitsas |
max_edges_per_cell | For |
max_feature_cells | For |
Value
A vector of lengthx.
See Also
See pairwise predicate functions (e.g.,s2_intersects()).
Examples
city_names <- c("Vatican City", "San Marino", "Luxembourg")cities <- s2_data_cities(city_names)country_names <- s2_data_tbl_countries$namecountries <- s2_data_countries()# closest feature returns y indices of the closest feature# for each feature in xcountry_names[s2_closest_feature(cities, countries)]# farthest feature returns y indices of the farthest feature# for each feature in xcountry_names[s2_farthest_feature(cities, countries)]# use s2_closest_edges() to find the k-nearest neighboursnearest <- s2_closest_edges(cities, cities, k = 2, min_distance = 0)city_namescity_names[unlist(nearest)]# predicate matricescountry_names[s2_intersects_matrix(cities, countries)[[1]]]# distance matricess2_distance_matrix(cities, cities)s2_max_distance_matrix(cities, countries[1:4])S2 Geography Predicates
Description
These functions operate two geography vectors (pairwise), and returna logical vector.
Usage
s2_contains(x, y, options = s2_options(model = "open"))s2_within(x, y, options = s2_options(model = "open"))s2_covered_by(x, y, options = s2_options(model = "closed"))s2_covers(x, y, options = s2_options(model = "closed"))s2_disjoint(x, y, options = s2_options())s2_intersects(x, y, options = s2_options())s2_equals(x, y, options = s2_options())s2_intersects_box( x, lng1, lat1, lng2, lat2, detail = 1000, options = s2_options())s2_touches(x, y, options = s2_options())s2_dwithin(x, y, distance, radius = s2_earth_radius_meters())s2_prepared_dwithin(x, y, distance, radius = s2_earth_radius_meters())Arguments
x,y | geography vectors. These inputsare passed to |
options | An |
lng1,lat1,lng2,lat2 | A latitude/longitude range |
detail | The number of points with which to approximatenon-geodesic edges. |
distance | A distance on the surface of the earth in the same unitsas |
radius | Radius of the earth. Defaults to the average radius ofthe earth in meters as defined by |
Model
The geometry model indicates whether or not a geometry includes its boundaries.Boundaries of line geometries are its end points.OPEN geometries do not contain their boundary (model = "open"); CLOSEDgeometries (model = "closed") contain their boundary; SEMI-OPEN geometries(model = "semi-open") contain half of their boundaries, such that when two polygonsdo not overlap or two lines do not cross, no point exist that belong tomore than one of the geometries. (This latter form, half-closed, isnot present in the OpenGIS "simple feature access" (SFA) standard nor DE9-IM onwhich that is based). The default values fors2_contains() (open)and covers/covered_by (closed) correspond to the SFA standard specificationof these operators.
See Also
Matrix versions of these predicates (e.g.,s2_intersects_matrix()).
BigQuery's geography function reference:
Examples
s2_contains( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"))s2_within( c("POINT (5 5)", "POINT (-1 1)"), "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")s2_covered_by( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"))s2_covers( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"))s2_disjoint( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"))s2_intersects( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"))s2_equals( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POLYGON ((10 0, 10 10, 0 10, 0 0, 10 0))", "POLYGON ((-1 -1, 10 0, 10 10, 0 10, -1 -1))" ))s2_intersects( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"))s2_intersects_box( c("POINT (5 5)", "POINT (-1 1)"), 0, 0, 10, 10)s2_touches( "POLYGON ((0 0, 0 1, 1 1, 0 0))", c("POINT (0 0)", "POINT (0.5 0.75)", "POINT (0 0.5)"))s2_dwithin( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"), 0 # distance in meters)s2_dwithin( "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", c("POINT (5 5)", "POINT (-1 1)"), 1e6 # distance in meters)Example Geometries
Description
These geometries are toy examples useful for testing various coordinateshuffling operations in the s2 package.
Usage
s2_data_example_wktFormat
An object of classlist of length 29.
Low-resolution world boundaries, timezones, and cities
Description
Well-known binary versions of theNatural Earthlow-resolution world boundaries and timezone boundaries.
Usage
s2_data_tbl_countriess2_data_tbl_timezoness2_data_tbl_citiess2_data_countries(name = NULL)s2_data_timezones(utc_offset_min = NULL, utc_offset_max = utc_offset_min)s2_data_cities(name = NULL)Arguments
name | The name of a country, continent, city, or |
utc_offset_min,utc_offset_max | Minimum and/or maximum timezoneoffsets. |
Format
A data.frame with columnsname (character), andgeometry (wk_wkb)
An object of classdata.frame with 120 rows and 2 columns.
An object of classdata.frame with 243 rows and 3 columns.
Source
Examples
head(s2_data_countries())s2_data_countries("Germany")s2_data_countries("Europe")head(s2_data_timezones())s2_data_timezones(-4)head(s2_data_cities())s2_data_cities("Cairo")Earth Constants
Description
According to Yoder (1995), the radius of the earth is6371.01 km. These functions are used to set thedefault radis for functions that return a distanceor accept a distance as input(e.g.,s2_distance() ands2_dwithin()).
Usage
s2_earth_radius_meters()References
Yoder, C.F. 1995. "Astrometric and Geodetic Properties of Earth and theSolar System" in Global Earth Physics, A Handbook of Physical Constants,AGU Reference Shelf 1, American Geophysical Union, Table 2.doi:10.1029/RF001p0001
Examples
s2_earth_radius_meters()Create and Format Geography Vectors
Description
These functions create and exportgeography vectors.Unlike the BigQuery geography constructors, these functions do not sanitizeinvalid or redundant input usings2_union(). Note that when creating polygonsusings2_make_polygon(), rings can be open or closed.
Usage
s2_geog_point(longitude, latitude)s2_make_line(longitude, latitude, feature_id = 1L)s2_make_polygon( longitude, latitude, feature_id = 1L, ring_id = 1L, oriented = FALSE, check = TRUE)s2_geog_from_text( wkt_string, oriented = FALSE, check = TRUE, planar = FALSE, tessellate_tol_m = s2_tessellate_tol_default())s2_geog_from_wkb( wkb_bytes, oriented = FALSE, check = TRUE, planar = FALSE, tessellate_tol_m = s2_tessellate_tol_default())s2_as_text( x, precision = 16, trim = TRUE, planar = FALSE, tessellate_tol_m = s2_tessellate_tol_default())s2_as_binary( x, endian = wk::wk_platform_endian(), planar = FALSE, tessellate_tol_m = s2_tessellate_tol_default())s2_tessellate_tol_default()Arguments
longitude,latitude | Vectors of latitude and longitude |
feature_id,ring_id | Vectors for which a change insequential values indicates a new feature or ring. Use |
oriented | TRUE if polygon ring directions are known to be correct(i.e., exterior rings are defined counter clockwise and interiorrings are defined clockwise). |
check | Use |
wkt_string | Well-known text |
planar | Use |
tessellate_tol_m | The maximum number of meters to that a point mustbe moved to satisfy the planar edge constraint. |
wkb_bytes | A |
x | An object that can be converted to an s2_geography vector |
precision | The number of significant digits to export whenwriting well-known text. If |
trim | Should trailing zeroes be included after the decimal place? |
endian | The endian-ness of the well-known binary. See |
See Also
Seeas_s2_geography() for other ways to construct geography vectors.
BigQuery's geography function reference:
Examples
# create point geographies using coordinate values:s2_geog_point(-64, 45)# create line geographies using coordinate values:s2_make_line(c(-64, 8), c(45, 71))# optionally, separate features using feature_id:s2_make_line( c(-64, 8, -27, -27), c(45, 71, 0, 45), feature_id = c(1, 1, 2, 2))# create polygon geographies using coordinate values:# (rings can be open or closed)s2_make_polygon(c(-45, 8, 0), c(64, 71, 90))# optionally, separate rings and/or features using# ring_id and/or feature_ids2_make_polygon( c(20, 10, 10, 30, 45, 30, 20, 20, 40, 20, 45), c(35, 30, 10, 5, 20, 20, 15, 25, 40, 45, 30), feature_id = c(rep(1, 8), rep(2, 3)), ring_id = c(1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1))# import and export well-known text(geog <- s2_geog_from_text("POINT (-64 45)"))s2_as_text(geog)# import and export well-known binary(geog <- s2_geog_from_wkb(wk::as_wkb("POINT (-64 45)")))s2_as_binary(geog)# import geometry from planar spaces2_geog_from_text( "POLYGON ((0 0, 1 0, 0 1, 0 0))", planar = TRUE, tessellate_tol_m = 1)# export geographies into planar spacegeog <- s2_make_polygon(c(179, -179, 179), c(10, 10, 11))s2_as_text(geog, planar = TRUE)# polygons containing a pole need an extra stepgeog <- s2_data_countries("Antarctica")geom <- s2_as_text( s2_intersection(geog, s2_world_plate_carree()), planar = TRUE)S2 Geography Accessors
Description
Accessors extract information aboutgeography vectors.
Usage
s2_is_collection(x)s2_is_valid(x)s2_is_valid_detail(x)s2_dimension(x)s2_num_points(x)s2_is_empty(x)s2_area(x, radius = s2_earth_radius_meters())s2_length(x, radius = s2_earth_radius_meters())s2_perimeter(x, radius = s2_earth_radius_meters())s2_x(x)s2_y(x)s2_distance(x, y, radius = s2_earth_radius_meters())s2_max_distance(x, y, radius = s2_earth_radius_meters())Arguments
x,y | geography vectors. These inputsare passed to |
radius | Radius of the earth. Defaults to the average radius ofthe earth in meters as defined by |
See Also
BigQuery's geography function reference:
Examples
# s2_is_collection() tests for multiple geometries in one features2_is_collection(c("POINT (-64 45)", "MULTIPOINT ((-64 45), (8 72))"))# s2_dimension() returns 0 for point, 1 for line, 2 for polygons2_dimension( c( "GEOMETRYCOLLECTION EMPTY", "POINT (-64 45)", "LINESTRING (-64 45, 8 72)", "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", "GEOMETRYCOLLECTION (POINT (-64 45), LINESTRING (-64 45, 8 72))" ))# s2_num_points() counts pointss2_num_points(c("POINT (-64 45)", "LINESTRING (-64 45, 8 72)"))# s2_is_empty tests for emptinesss2_is_empty(c("POINT (-64 45)", "POINT EMPTY"))# calculate area, length, and perimeters2_area("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))")s2_perimeter("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))")s2_length(s2_boundary("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))"))# extract x and y coordinates from pointss2_x(c("POINT (-64 45)", "POINT EMPTY"))s2_y(c("POINT (-64 45)", "POINT EMPTY"))# calculate minimum and maximum distance between two geometriess2_distance( "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", "POINT (-64 45)")s2_max_distance( "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", "POINT (-64 45)")Create an S2 LngLat Vector
Description
This class represents a latitude and longitude on the Earth's surface.Most calculations in S2 convert this to aas_s2_point(), which is aunit vector representation of this value.
Usage
s2_lnglat(lng, lat)as_s2_lnglat(x, ...)## Default S3 method:as_s2_lnglat(x, ...)## S3 method for class 'wk_xy'as_s2_lnglat(x, ...)## S3 method for class 'wk_xyz'as_s2_lnglat(x, ...)Arguments
lat,lng | Vectors of latitude and longitude values in degrees. |
x | A |
... | Unused |
Value
An object with class s2_lnglat
Examples
s2_lnglat(45, -64) # Halifax, Nova Scotia!as.data.frame(s2_lnglat(45, -64))Geography Operation Options
Description
These functions specify defaults for options used to perform operationsand construct geometries. These are used in predicates (e.g.,s2_intersects()),and boolean operations (e.g.,s2_intersection()) to specify the model forcontainment and how new geometries should be constructed.
Usage
s2_options( model = NULL, snap = s2_snap_identity(), snap_radius = -1, duplicate_edges = FALSE, edge_type = "directed", validate = FALSE, polyline_type = "path", polyline_sibling_pairs = "keep", simplify_edge_chains = FALSE, split_crossing_edges = FALSE, idempotent = FALSE, dimensions = c("point", "polyline", "polygon"))s2_snap_identity()s2_snap_level(level)s2_snap_precision(precision)s2_snap_distance(distance)Arguments
model | One of 'open', 'semi-open' (default for polygons),or 'closed' (default for polylines). See section 'Model' |
snap | Use |
snap_radius | As opposed to the snap function, which specifiesthe maximum distance a vertex should move, the snap radius (in radians) setsthe minimum distance between vertices of the output that don't cause verticesto move more than the distance specified by the snap function. This can be usedto simplify the result of a boolean operation. Use -1 to specify that anyminimum distance is acceptable. |
duplicate_edges | Use |
edge_type | One of 'directed' (default) or 'undirected'. |
validate | Use |
polyline_type | One of 'path' (default) or 'walk'. If 'walk',polylines that backtrack are preserved. |
polyline_sibling_pairs | One of 'discard' (default) or 'keep'. |
simplify_edge_chains | Use |
split_crossing_edges | Use |
idempotent | Use |
dimensions | A combination of 'point', 'polyline', and/or 'polygon'that can used to constrain the output of |
level | A value from 0 to 30 corresponding to the cell levelat which snapping should occur. |
precision | A number by which coordinates should be multipliedbefore being rounded. Rounded to the nearest exponent of 10. |
distance | A distance (in radians) denoting the maximumdistance a vertex should move in the snapping process. |
Model
The geometry model indicates whether or not a geometry includes its boundaries.Boundaries of line geometries are its end points.OPEN geometries do not contain their boundary (model = "open"); CLOSEDgeometries (model = "closed") contain their boundary; SEMI-OPEN geometries(model = "semi-open") contain half of their boundaries, such that when two polygonsdo not overlap or two lines do not cross, no point exist that belong tomore than one of the geometries. (This latter form, half-closed, isnot present in the OpenGIS "simple feature access" (SFA) standard nor DE9-IM onwhich that is based). The default values fors2_contains() (open)and covers/covered_by (closed) correspond to the SFA standard specificationof these operators.
Examples
# use s2_options() to specify containment models, snap level# layer creation options, and builder optionss2_options(model = "closed", snap = s2_snap_level(30))Plot S2 Geographies
Description
Plot S2 Geographies
Usage
s2_plot( x, ..., asp = 1, xlab = "", ylab = "", rule = "evenodd", add = FALSE, plot_hemisphere = FALSE, simplify = TRUE, centre = NULL)Arguments
x | |
... | Passed to plotting functions for features: |
asp,xlab,ylab | Passed to |
rule | The rule to use for filling polygons (see |
add | Should a new plot be created, or should |
plot_hemisphere | Plot the outline of the earth |
simplify | Use |
centre | The longitude/latitude point of the centre of theorthographic projection |
Value
The input, invisibly
Examples
s2_plot(s2_data_countries())s2_plot(s2_data_cities(), add = TRUE)Create an S2 Point Vector
Description
In S2 terminology, a "point" is a 3-dimensional unit vector representationof ans2_point(). Internally, all s2 objects are stored as3-dimensional unit vectors.
Usage
s2_point(x, y, z)s2_point_crs()as_s2_point(x, ...)## Default S3 method:as_s2_point(x, ...)## S3 method for class 'wk_xy'as_s2_point(x, ...)## S3 method for class 'wk_xyz'as_s2_point(x, ...)Arguments
x,y,z | Vectors of latitude and longitude values in degrees. |
... | Unused |
Value
An object with class s2_point
Examples
point <- s2_lnglat(-64, 45) # Halifax, Nova Scotia!as_s2_point(point)as.data.frame(as_s2_point(point))Linear referencing
Description
Linear referencing
Usage
s2_project(x, y, radius = s2_earth_radius_meters())s2_project_normalized(x, y)s2_interpolate(x, distance, radius = s2_earth_radius_meters())s2_interpolate_normalized(x, distance_normalized)Arguments
x | A simple polyline geography vector |
y | A simple point geography vector. The point will besnapped to the nearest point on |
radius | Radius of the earth. Defaults to the average radius ofthe earth in meters as defined by |
distance | A distance along |
distance_normalized | A |
Value
s2_interpolate()returns the point onx,distancemetersalong the line.s2_interpolate_normalized()returns the point onxinterpolatedto a fraction along the line.s2_project()returns thedistancethatpointoccurs alongx.s2_project_normalized()returns thedistance_normalizedalongxwherepointoccurs.
Examples
s2_project_normalized("LINESTRING (0 0, 0 90)", "POINT (0 22.5)")s2_project("LINESTRING (0 0, 0 90)", "POINT (0 22.5)")s2_interpolate_normalized("LINESTRING (0 0, 0 90)", 0.25)s2_interpolate("LINESTRING (0 0, 0 90)", 2501890)Low-level wk filters and handlers
Description
Low-level wk filters and handlers
Usage
## S3 method for class 's2_geography'wk_handle( handleable, handler, ..., s2_projection = s2_projection_plate_carree(), s2_tessellate_tol = Inf)s2_geography_writer( oriented = FALSE, check = TRUE, projection = s2_projection_plate_carree(), tessellate_tol = Inf)## S3 method for class 's2_geography'wk_writer(handleable, ...)s2_trans_point()s2_trans_lnglat()s2_projection_plate_carree(x_scale = 180)s2_projection_mercator(x_scale = 20037508.3427892)s2_hemisphere(centre)s2_world_plate_carree(epsilon_east_west = 0, epsilon_north_south = 0)s2_projection_orthographic(centre = s2_lnglat(0, 0))Arguments
handleable | A geometry vector (e.g., |
handler | Awk_handler object. |
... | Passed to the |
oriented | TRUE if polygon ring directions are known to be correct(i.e., exterior rings are defined counter clockwise and interiorrings are defined clockwise). |
check | Use |
projection,s2_projection | One of |
tessellate_tol,s2_tessellate_tol | An angle in radians.Points will not be added if a line segment is within thisdistance of a point. |
x_scale | The maximum x value of the projection |
centre | The center point of the orthographic projection |
epsilon_east_west,epsilon_north_south | Use a positive number todefine the edges of a Cartesian world slightly inward from -180, -90,180, 90. This may be used to define a world outline for a projection whereprojecting at the extreme edges of the earth results in a non-finite value. |
Value
s2_projection_plate_carree(),s2_projection_mercator(): An external pointerto an S2 projection.