Module: H3::GeoJson
- Included in:
- H3
- Defined in:
- lib/h3/geo_json.rb
Overview
GeoJSON helper methods.
This module allows conversions between GeoJSON polygon data and a nested set of coordinates.
It should be noted that H3 describes coordinates as number pairs in the form
[latitude, longitude]
whereas the GeoJSON standard uses
[longitude, latitude]
Both use degrees.
Coordinates Array
We use a nested array to hold coordinates describing a geographical region.
The first element in the array is an external geofence boundary, composed of an array of coordinates as 2-element arrays of the form [latitude, longitude].
Any further elements in the array are further geofence arrays of coordinates which describe holes that may be present in the polygon.
Specific examples are shown in the individual method details.
Instance Method Summary collapse
-
#coordinates_to_geo_json(coordinates) ⇒ String
Convert a nested array of coordinates to a GeoJSON document.
-
#geo_json_to_coordinates(input) ⇒ Array<Array<Array>>
Convert a GeoJSON document to a nested array of coordinates.
Instance Method Details
#coordinates_to_geo_json(coordinates) ⇒ String
Convert a nested array of coordinates to a GeoJSON document
132 133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/h3/geo_json.rb', line 132 def coordinates_to_geo_json(coordinates) coordinates = swap_lat_lon(coordinates) outer_coords, *inner_coords = coordinates factory = RGeo::Cartesian.simple_factory exterior = factory.linear_ring(outer_coords.map { |lon, lat| factory.point(lon, lat) }) interior_rings = inner_coords.map do |polygon| factory.linear_ring(polygon.map { |lon, lat| factory.point(lon, lat) }) end polygon = factory.polygon(exterior, interior_rings) RGeo::GeoJSON.encode(polygon).to_json rescue RGeo::Error::InvalidGeometry, NoMethodError invalid_coordinates! end |
#geo_json_to_coordinates(input) ⇒ Array<Array<Array>>
Convert a GeoJSON document to a nested array of coordinates.
78 79 80 81 82 83 84 |
# File 'lib/h3/geo_json.rb', line 78 def geo_json_to_coordinates(input) geom = RGeo::GeoJSON.decode(input) coordinates = fetch_coordinates(geom) swap_lat_lon(coordinates) || failed_to_parse! rescue JSON::ParserError failed_to_parse! end |