diff --git a/spec/geo/polygon_spec.cr b/spec/geo/polygon_spec.cr index afaf15b..0b9c7c1 100644 --- a/spec/geo/polygon_spec.cr +++ b/spec/geo/polygon_spec.cr @@ -119,6 +119,19 @@ describe Geo::Polygon do geojson.should be_a(GeoJSON::Polygon) end + describe "#to_wkt" do + it "outputs a Well Known Text format" do + polygon = Geo::Polygon.new([ + Geo::Coord.new(10, 30), + Geo::Coord.new(20, 10), + Geo::Coord.new(40, 20), + Geo::Coord.new(40, 40), + ]) + + polygon.to_wkt.should eq "POLYGON((30 10, 10 20, 20 40, 40 40, 30 10))" + end + end + describe "comparisons" do describe "equality" do polygon1 = Geo::Polygon.new([pos1, pos2]) diff --git a/src/geo/coord.cr b/src/geo/coord.cr index 157ed79..de8dab5 100644 --- a/src/geo/coord.cr +++ b/src/geo/coord.cr @@ -174,11 +174,11 @@ module Geo String.build { |str| to_ewkt str } end - def to_ewkt(io : IO) : Nil + def to_ewkt(io : IO, output_type = true, output_parentheses = true) : Nil # SRID 4326 is used for latitude and longitude # https://epsg.org/crs_4326/WGS-84.html io << "SRID=4326;" - to_wkt io + to_wkt io, output_type: output_type, output_parentheses: output_parentheses end def to_ewkb(bytes : Bytes = Bytes.new(23), byte_format : IO::ByteFormat = IO::ByteFormat::BigEndian) : Bytes @@ -194,10 +194,11 @@ module Geo String.build { |str| to_wkt str } end - def to_wkt(io : IO) : Nil - io << "POINT(" + def to_wkt(io : IO, output_type = true, output_parentheses = true) : Nil + io << "POINT" if output_type + io << '(' if output_parentheses io << lng << ' ' << lat - io << ')' + io << ')' if output_parentheses end def to_wkb(bytes : Bytes = Bytes.new(21), byte_format : IO::ByteFormat = IO::ByteFormat::BigEndian) : Bytes diff --git a/src/geo/polygon.cr b/src/geo/polygon.cr index 3ac2b15..8f9c353 100644 --- a/src/geo/polygon.cr +++ b/src/geo/polygon.cr @@ -106,6 +106,21 @@ module Geo GeoJSON::Polygon.new([coordinates]) end + def to_wkt : String + String.build { |str| to_wkt str } + end + + def to_wkt(io : IO) : Nil + io << "POLYGON((" + @coords.each_with_index 1 do |coord, index| + coord.to_wkt io, output_type: false, output_parentheses: false + if index < @coords.size + io << ", " + end + end + io << "))" + end + private def calculate_centroid : Geo::Coord centroid_lat = 0.0 centroid_lng = 0.0