Skip to content

Commit

Permalink
Add Polygon#to_wkt
Browse files Browse the repository at this point in the history
  • Loading branch information
jgaskins committed Dec 31, 2024
1 parent 4fc2de6 commit 2e6ed8e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
13 changes: 13 additions & 0 deletions spec/geo/polygon_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
11 changes: 6 additions & 5 deletions src/geo/coord.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
15 changes: 15 additions & 0 deletions src/geo/polygon.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 2e6ed8e

Please sign in to comment.