Class: Geoq::GeomReader

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/geoq/geom_reader.rb

Constant Summary collapse

GH_REGEX =
Regexp.new(/\A[#{BASE_32}]+\z/)
LAT_LON_REGEX =
/\A-?\d+\.?\d*,-?\d+\.?\d*\z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(instream) ⇒ GeomReader

Returns a new instance of GeomReader.



17
18
19
20
21
# File 'lib/geoq/geom_reader.rb', line 17

def initialize(instream)
  @instream = instream
  @wkt = RGeo::WKRep::WKTParser.new
  @factory = RGeo::Cartesian.factory
end

Instance Attribute Details

#wktObject (readonly)

Returns the value of attribute wkt.



9
10
11
# File 'lib/geoq/geom_reader.rb', line 9

def wkt
  @wkt
end

Instance Method Details

#decode(line) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/geoq/geom_reader.rb', line 29

def decode(line)
  if geohash?(line)
    (lat1, lon1), (lat2, lon2) = GeoHash.decode(line)
    p1 = factory.point(lon1, lat1)
    p2 = factory.point(lon2, lat2)
    geom = RGeo::Cartesian::BoundingBox.create_from_points(p1, p2).to_geometry
    [Geohash.new(geom, strip_whitespace(line))]
  elsif geojson?(line)
    decoded = RGeo::GeoJSON.decode(line)
    case decoded
    when RGeo::GeoJSON::FeatureCollection
      decoded.map { |f| GeoJson.new(f, line) }
    else
      [GeoJson.new(decoded, line)]
    end
  elsif latlon?(line)
    [LatLon.new(factory.point(*(strip_whitespace(line.gsub("\t", ",")).split(",").map(&:to_f).reverse)), line)]
  else
    [Wkt.new(wkt.parse(line), line)]
  end
end

#each(&block) ⇒ Object



23
24
25
26
27
# File 'lib/geoq/geom_reader.rb', line 23

def each(&block)
  instream.each_line do |l|
    decode(l).each(&block)
  end
end

#geohash?(line) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/geoq/geom_reader.rb', line 55

def geohash?(line)
  !!GH_REGEX.match(strip_whitespace(line))
end

#geojson?(line) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/geoq/geom_reader.rb', line 59

def geojson?(line)
  line.lstrip.start_with?("{")
end

#latlon?(line) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/geoq/geom_reader.rb', line 63

def latlon?(line)
  !!LAT_LON_REGEX.match(strip_whitespace(line.gsub(/\t/, ",")))
end

#strip_whitespace(line) ⇒ Object



51
52
53
# File 'lib/geoq/geom_reader.rb', line 51

def strip_whitespace(line)
  line.gsub(/\s+/, "").downcase
end