From 0ea4fd7a9c3be48bdcdf61e60996ce2ebe46c5c3 Mon Sep 17 00:00:00 2001 From: Anton Maminov Date: Thu, 11 Apr 2024 15:24:36 +0300 Subject: [PATCH] add geocrystal/geojson and to_geojson methods --- shard.yml | 2 ++ spec/geo/coord_spec.cr | 8 ++++++++ spec/geo/polygon_spec.cr | 18 ++++++++++++++++++ src/geo.cr | 1 + src/geo/coord.cr | 4 ++++ src/geo/polygon.cr | 6 ++++++ 6 files changed, 39 insertions(+) diff --git a/shard.yml b/shard.yml index a55b005..9c2242b 100644 --- a/shard.yml +++ b/shard.yml @@ -16,6 +16,8 @@ dependencies: github: geocrystal/geo_bearing ring_area: github: geocrystal/ring_area + geojson: + github: geocrystal/geojson development_dependencies: ameba: diff --git a/spec/geo/coord_spec.cr b/spec/geo/coord_spec.cr index e9bf473..a95c5db 100644 --- a/spec/geo/coord_spec.cr +++ b/spec/geo/coord_spec.cr @@ -103,6 +103,14 @@ describe Geo::Coord do end end + describe "#to_geojson" do + coord = Geo::Coord.new(-15, 125) + + geojson = coord.to_geojson + + geojson.should be_a(GeoJSON::Coordinates) + end + describe "comparisons" do describe "equality" do pos1 = Geo::Coord.new(45.3142533036254, -93.47527313511819) diff --git a/spec/geo/polygon_spec.cr b/spec/geo/polygon_spec.cr index 73b213c..94c88d0 100644 --- a/spec/geo/polygon_spec.cr +++ b/spec/geo/polygon_spec.cr @@ -100,6 +100,24 @@ describe Geo::Polygon do it { polygon.area.should eq(7748891609977.457) } end + describe "#to_geojson" do + coords = [ + Geo::Coord.new(-15, 125), + Geo::Coord.new(-22, 113), + Geo::Coord.new(-37, 117), + Geo::Coord.new(-33, 130), + Geo::Coord.new(-39, 148), + Geo::Coord.new(-27, 154), + Geo::Coord.new(-15, 144), + Geo::Coord.new(-15, 125), + ] + + polygon = Geo::Polygon.new(coords) + geojson = polygon.to_geojson + + geojson.should be_a(GeoJSON::Polygon) + end + describe "comparisons" do describe "equality" do polygon1 = Geo::Polygon.new([pos1, pos2]) diff --git a/src/geo.cr b/src/geo.cr index 104323b..76a70d5 100644 --- a/src/geo.cr +++ b/src/geo.cr @@ -3,6 +3,7 @@ require "geohash" require "geo_bearing" require "haversine" require "ring_area" +require "geojson" require "./geo/utils" require "./geo/coord" require "./geo/polygon" diff --git a/src/geo/coord.cr b/src/geo/coord.cr index e7e14f3..9d9aa62 100644 --- a/src/geo/coord.cr +++ b/src/geo/coord.cr @@ -156,6 +156,10 @@ module Geo Geohash.encode(lat.to_f, lng.to_f, precision) end + def to_geojson : GeoJSON::Coordinates + GeoJSON::Coordinates.new(lng.to_f64, lat.to_f64) + end + # Returns a string representing coordinates. # # ``` diff --git a/src/geo/polygon.cr b/src/geo/polygon.cr index fd54eb6..0a7ea4a 100644 --- a/src/geo/polygon.cr +++ b/src/geo/polygon.cr @@ -100,6 +100,12 @@ module Geo size == other.size end + def to_geojson : GeoJSON::Polygon + coordinates = @coords.map { |coord| GeoJSON::Coordinates.new(coord.lng.to_f64, coord.lat.to_f64) } + + GeoJSON::Polygon.new([coordinates]) + end + private def calculate_centroid : Geo::Coord centroid_lat = 0.0 centroid_lng = 0.0