Class: NSWTopo::Map
- Inherits:
-
Object
- Object
- NSWTopo::Map
- Extended by:
- Forwardable
- Defined in:
- lib/nswtopo/map.rb
Constant Summary
Constants included from Formats
Formats::ARGS, Formats::PPI, Formats::TILE
Constants included from Log
Log::FAILURE, Log::NEUTRAL, Log::SUCCESS, Log::UPDATE
Constants included from Dither
Instance Attribute Summary collapse
-
#centre ⇒ Object
readonly
Returns the value of attribute centre.
-
#dimensions ⇒ Object
readonly
Returns the value of attribute dimensions.
-
#projection ⇒ Object
readonly
Returns the value of attribute projection.
-
#rotation ⇒ Object
readonly
Returns the value of attribute rotation.
-
#scale ⇒ Object
readonly
Returns the value of attribute scale.
Class Method Summary collapse
- .declination(longitude, latitude) ⇒ Object
- .from_svg(archive, svg_path) ⇒ Object
- .init(archive, scale: 25000, rotation: 0.0, bounds: nil, coords: nil, dimensions: nil, inset: [], margins: nil) ⇒ Object
- .load(archive) ⇒ Object
Instance Method Summary collapse
- #add(*layers, after: nil, before: nil, replace: nil, overwrite: false, strict: false) ⇒ Object
- #cutline(mm: nil) ⇒ Object
- #declination ⇒ Object
- #delete(*names) ⇒ Object
- #geotransform(resolution: nil, ppi: nil) ⇒ Object
- #info(empty: nil, json: false, proj: false, wkt: false) ⇒ Object (also: #to_s)
-
#initialize(archive, neatline:, centre:, dimensions:, scale:, rotation:, layers: {}) ⇒ Map
constructor
A new instance of Map.
- #layers ⇒ Object
- #move(name, before: nil, after: nil) ⇒ Object
- #neatline(mm: nil) ⇒ Object
- #render(*paths, worldfile: false, force: false, background: nil, **options) ⇒ Object
- #save ⇒ Object
- #te ⇒ Object
- #to_metres(mm) ⇒ Object
- #to_mm(metres) ⇒ Object
- #write_pam_file(path, **opts) ⇒ Object
- #write_world_file(path, **opts) ⇒ Object
Methods included from Formats
===, extensions, #neatline_path_data, #rasterise, #render_gemf, #render_jpg, #render_kmz, #render_mbtiles, #render_pdf, #render_png, #render_svg, #render_svgz, #render_tif, #render_zip
Methods included from Log
#log_abort, #log_neutral, #log_success, #log_update, #log_warn
Methods included from Dither
Methods included from Zip
Methods included from Safely
Methods included from TiledWebMap
Constructor Details
#initialize(archive, neatline:, centre:, dimensions:, scale:, rotation:, layers: {}) ⇒ Map
Returns a new instance of Map.
5 6 7 8 9 10 11 12 |
# File 'lib/nswtopo/map.rb', line 5 def initialize(archive, neatline:, centre:, dimensions:, scale:, rotation:, layers: {}) @archive, @neatline, @centre, @dimensions, @scale, @rotation, @layers = archive, neatline, centre, dimensions, scale, rotation, layers params = { k_0: 1.0 / @scale, units: "mm", x_0: 0.0005 * @dimensions[0], y_0: 0.0005 * @dimensions[1] } @projection = rotation.zero? ? Projection.transverse_mercator(*centre, **params) : Projection.oblique_mercator(*centre, alpha: rotation, **params) @cutline = @neatline.reproject_to(@projection) end |
Instance Attribute Details
#centre ⇒ Object (readonly)
Returns the value of attribute centre.
13 14 15 |
# File 'lib/nswtopo/map.rb', line 13 def centre @centre end |
#dimensions ⇒ Object (readonly)
Returns the value of attribute dimensions.
13 14 15 |
# File 'lib/nswtopo/map.rb', line 13 def dimensions @dimensions end |
#projection ⇒ Object (readonly)
Returns the value of attribute projection.
13 14 15 |
# File 'lib/nswtopo/map.rb', line 13 def projection @projection end |
#rotation ⇒ Object (readonly)
Returns the value of attribute rotation.
13 14 15 |
# File 'lib/nswtopo/map.rb', line 13 def rotation @rotation end |
#scale ⇒ Object (readonly)
Returns the value of attribute scale.
13 14 15 |
# File 'lib/nswtopo/map.rb', line 13 def scale @scale end |
Class Method Details
.declination(longitude, latitude) ⇒ Object
209 210 211 212 213 214 215 216 217 |
# File 'lib/nswtopo/map.rb', line 209 def self.declination(longitude, latitude) today = Date.today query = { latd: latitude, lond: longitude, latm: 0, lonm: 0, lats: 0, lons: 0, elev: 0, year: today.year, month: today.month, day: today.day, Ein: "Dtrue" } uri = URI::HTTPS.build host: "api.geomagnetism.ga.gov.au", path: "/agrf", query: URI.encode_www_form(query) json = Net::HTTP.get uri Float(JSON.parse(json).dig("magneticFields", "D").to_s.sub(/ .*/, "")) rescue JSON::ParserError, ArgumentError, TypeError, SystemCallError, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, SocketError raise "couldn't get magnetic declination value" end |
.from_svg(archive, svg_path) ⇒ Object
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/nswtopo/map.rb', line 130 def self.from_svg(archive, svg_path) xml = REXML::Document.new(svg_path.read) creator_tool = xml.elements["svg/metadata/rdf:RDF/rdf:Description[@xmp:CreatorTool]/@xmp:CreatorTool"]&.value version = Version[creator_tool] raise "SVG nswtopo version too old: %s" % svg_path unless version >= MIN_VERSION raise "SVG nswtopo version too new: %s" % svg_path unless version <= VERSION /^0\s+0\s+(?<width>\S+)\s+(?<height>\S+)$/ =~ xml.elements["svg[@viewBox]/@viewBox"]&.value width && xml.elements["svg[ @width='#{ width}mm']"] || raise(Version::Error) height && xml.elements["svg[@height='#{height}mm']"] || raise(Version::Error) dimensions = [width, height].map(&:to_f) = xml.elements["svg/metadata/nswtopo:map[@projection][@centre][@scale][@rotation]"] || raise(Version::Error) projection = Projection.new .attributes["projection"] neatline = GeoJSON.polygon JSON.parse(.attributes["neatline"]), projection: projection centre = JSON.parse .attributes["centre"] scale = .attributes["scale"].to_i rotation = .attributes["rotation"].to_f new(archive, neatline: neatline, centre: centre, dimensions: dimensions, scale: scale, rotation: rotation).save.tap do |map| map.write "map.svg", svg_path.read end rescue Version::Error, JSON::ParserError raise "not an nswtopo SVG file: %s" % svg_path rescue SystemCallError raise "couldn't read file: %s" % svg_path rescue REXML::ParseException raise "unrecognised map file: %s" % svg_path end |
.init(archive, scale: 25000, rotation: 0.0, bounds: nil, coords: nil, dimensions: nil, inset: [], margins: nil) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/nswtopo/map.rb', line 18 def self.init(archive, scale: 25000, rotation: 0.0, bounds: nil, coords: nil, dimensions: nil, inset: [], margins: nil) points = case when dimensions && margins raise "can't specify both margins and map dimensions" when coords && bounds raise "can't specify both bounds file and map coordinates" when coords coords when bounds gps = GPS.load(bounds).explode margins ||= [15, 15] unless dimensions || gps.polygons.any? case when gps.polygons.any? gps.polygons.flat_map(&:coordinates).inject(&:+) when gps.linestrings.any? gps.linestrings.map(&:coordinates).inject(&:+) when gps.points.any? gps.points.map(&:coordinates) else raise "no features found in %s" % bounds end else raise "no bounds file or map coordinates specified" end margins ||= [0, 0] centre = points.transpose.map(&:minmax).map(&:sum).times(0.5) equidistant = Projection.azimuthal_equidistant *centre case rotation when "auto" raise "can't specify both map dimensions and auto-rotation" if dimensions local_points = GeoJSON.multipoint(points).reproject_to(equidistant).coordinates local_centre, local_extents, rotation = local_points.minimum_bounding_box(*margins) rotation *= -180.0 / Math::PI when "magnetic" rotation = declination(*centre) else raise "map rotation must be between ±45°" unless rotation.abs <= 45 end unless dimensions || local_centre local_points = GeoJSON.multipoint(points).reproject_to(equidistant).coordinates local_centre, local_extents = local_points.map do |point| point.rotate_by_degrees rotation end.transpose.map(&:minmax).map do |min, max| [0.5 * (max + min), max - min] end.transpose local_centre.rotate_by_degrees! -rotation end unless dimensions dimensions = local_extents.times(1000.0 / scale).plus margins.times(2) centre = GeoJSON.point(local_centre, projection: equidistant).reproject_to_wgs84.coordinates end params = { units: "mm", axis: "esu", k_0: 1.0 / scale, x_0: 0.0005 * dimensions[0], y_0: -0.0005 * dimensions[1] } projection = rotation.zero? ? Projection.transverse_mercator(*centre, **params) : Projection.oblique_mercator(*centre, alpha: rotation, **params) case when dimensions.all?(&:positive?) when coords raise "not enough information to calculate map size – add more coordinates, or specify map dimensions or margins" when bounds raise "not enough information to calculate map size – check bounds file, or specify map dimensions or margins" end insets = inset.map do |inset| inset.each_slice(2).entries.transpose.map(&:sort) end.each.with_object GeoJSON::Collection.new(projection: projection, name: "insets") do |bounds, collection| dimensions.zip(bounds).each do |dimension, (min, max)| raise OptionParser::InvalidArgument, "inset falls outside map dimensions" unless max > 0 && min < dimension end collection.add_polygon [bounds.inject(&:product).values_at(0,2,3,1,0)] end neatline = if insets.any? OS.ogr2ogr *%w[-f GeoJSON -lco RFC7946=NO /vsistdout/ GeoJSON:/vsistdin/ -dialect sqlite -sql], " SELECT ST_Difference(BuildMbr(0,0,\#{dimensions.join ?,}), ST_Union(geometry)) AS geometry\n FROM insets\n SQL\n stdin.puts insets.to_json\n end.then do |json|\n GeoJSON::Collection.load(json, projection: projection, name: \"neatline\").explode\n end\n else\n ring = [[0, 0], dimensions].transpose.inject(&:product).values_at(0,2,3,1,0)\n GeoJSON.polygon [ring], projection: projection, name: \"neatline\"\n end\n\n raise OptionParser::InvalidArgument, \"inset covers map\" if neatline.none?\n raise OptionParser::InvalidArgument, \"inset creates non-contiguous map\" unless neatline.one?\n new(archive, neatline: neatline, centre: centre, dimensions: dimensions, scale: scale, rotation: rotation).save\nend\n" do |stdin| |
.load(archive) ⇒ Object
115 116 117 118 119 120 121 |
# File 'lib/nswtopo/map.rb', line 115 def self.load(archive) properties = YAML.load(archive.read "map.yml") neatline = GeoJSON::Collection.load(archive.read "map.json") new archive, neatline: neatline, **properties rescue ArgumentError, YAML::Exception, GeoJSON::Error raise NSWTopo::Archive::Invalid end |
Instance Method Details
#add(*layers, after: nil, before: nil, replace: nil, overwrite: false, strict: false) ⇒ Object
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/nswtopo/map.rb', line 223 def add(*layers, after: nil, before: nil, replace: nil, overwrite: false, strict: false) [%w[before after replace], [before, after, replace]].transpose.select(&:last).each do |option, name| next if self.layers.any? { |other| other.name == name } raise "no such layer: %s" % name end.map(&:first).combination(2).each do || raise OptionParser::AmbiguousOption, "can't specify --%s and --%s simultaneously" % end strict ||= layers.one? layers.inject [self.layers, false, replace || after, []] do |(layers, changed, follow, errors), layer| index = layers.index layer unless replace || after || before if overwrite || !layer.uptodate? layer.create log_success "%s layer: %s" % [layer.empty? ? "empty" : "added", layer.name] else log_neutral "kept existing layer: %s" % layer.name next layers, changed, layer.name, errors if index end layers.delete layer case when index when follow index = layers.index { |other| other.name == follow } index += 1 when before index = layers.index { |other| other.name == before } else index = layers.index { |other| (other <=> layer) > 0 } || -1 end next layers.insert(index, layer), true, layer.name, errors rescue ArcGIS::Connection::Error => error log_warn "couldn't download layer: #{layer.name}" next layers, changed, follow, errors << error rescue RuntimeError => error errors << error break layers, changed, follow, errors if strict log_warn error. next layers, changed, follow, errors end.tap do |ordered_layers, changed, follow, errors| if changed @layers.replace Hash[ordered_layers.map(&:pair)] replace ? delete(replace) : save end case when errors.none? when strict raise errors.first when errors.one? raise PartialFailureError, "failed to create layer" else raise PartialFailureError, "failed to create #{errors.length} layers" end end end |
#cutline(mm: nil) ⇒ Object
171 172 173 |
# File 'lib/nswtopo/map.rb', line 171 def cutline(mm: nil) mm ? @cutline.buffer(mm).explode : @cutline end |
#declination ⇒ Object
219 220 221 |
# File 'lib/nswtopo/map.rb', line 219 def declination Map.declination *@centre end |
#delete(*names) ⇒ Object
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/nswtopo/map.rb', line 278 def delete(*names) raise OptionParser::MissingArgument, "no layers specified" unless names.any? names.inject Set[] do |matched, name| matches = @layers.keys.grep(name) raise "no such layer: #{name}" if String === name && matches.none? matched.merge matches end.tap do |names| raise "no matching layers found" unless names.any? end.each do |name| params = @layers.delete name @archive.delete Layer.new(name, self, params).filename log_success "deleted layer: %s" % name end save end |
#geotransform(resolution: nil, ppi: nil) ⇒ Object
187 188 189 190 |
# File 'lib/nswtopo/map.rb', line 187 def geotransform(resolution: nil, ppi: nil) mm_per_px = ppi ? 25.4 / ppi : to_mm(resolution) [0.0, mm_per_px, 0.0, @dimensions[1], 0.0, -mm_per_px] end |
#info(empty: nil, json: false, proj: false, wkt: false) ⇒ Object Also known as: to_s
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
# File 'lib/nswtopo/map.rb', line 312 def info(empty: nil, json: false, proj: false, wkt: false) case when json bbox = @neatline.reproject_to_wgs84.first bbox.properties.merge! dimensions: @dimensions, scale: @scale, rotation: @rotation, layers: layers.map(&:name) JSON.pretty_generate bbox.to_h when proj OS.gdalsrsinfo("-o", "proj4", "--single-line", @projection) when wkt OS.gdalsrsinfo("-o", "wkt2", @projection).gsub(/\n\n+|\A\n+/, "") else area_km2 = @neatline.area * (0.000001 * @scale)**2 extents_km = @dimensions.times(0.000001 * @scale) StringIO.new.tap do |io| io.puts "%-11s 1:%i" % ["scale:", @scale] io.puts "%-11s %imm × %imm" % ["dimensions:", *@dimensions.map(&:round)] io.puts "%-11s %.1fkm × %.1fkm" % ["extent:", *extents_km] io.puts "%-11s %.1fkm²" % ["area:", area_km2] io.puts "%-11s %.1f°" % ["rotation:", @rotation] layers.reject(&empty ? :nil? : :empty?).inject("layers:") do |heading, layer| io.puts "%-11s %s" % [heading, layer] nil end end.string end end |
#layers ⇒ Object
161 162 163 164 165 |
# File 'lib/nswtopo/map.rb', line 161 def layers @layers.map do |name, params| Layer.new(name, self, params) end end |
#move(name, before: nil, after: nil) ⇒ Object
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/nswtopo/map.rb', line 294 def move(name, before: nil, after: nil) name, target = [name, before || after].map do |name| Layer.sanitise name end.each do |name| raise OptionParser::InvalidArgument, "no such layer: #{name}" unless @layers.key? name end raise OptionParser::InvalidArgument, "layers must be different" if name == target insert = [name, @layers.delete(name)] @layers.each.with_object [] do |(name, layer), layers| layers << insert if before && name == target layers << [name, layer] layers << insert if after && name == target end.tap do |layers| @layers.replace layers.to_h end save end |
#neatline(mm: nil) ⇒ Object
167 168 169 |
# File 'lib/nswtopo/map.rb', line 167 def neatline(mm: nil) mm ? @neatline.buffer(mm).explode : @neatline end |
#render(*paths, worldfile: false, force: false, background: nil, **options) ⇒ Object
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 |
# File 'lib/nswtopo/map.rb', line 340 def render(*paths, worldfile: false, force: false, background: nil, **) @archive.delete "map.svg" if force Dir.mktmppath do |temp_dir| rasters = Hash.new do |rasters, opts| png_path = temp_dir / "raster.#{rasters.size}.png" pam_path = temp_dir / "raster.#{rasters.size}.png.aux.xml" rasterise png_path, background: background, **opts write_pam_file pam_path, **opts rasters[opts] = png_path end dithers = Hash.new do |dithers, opts| png_path = temp_dir / "dither.#{dithers.size}.png" pam_path = temp_dir / "dither.#{dithers.size}.png.aux.xml" FileUtils.cp rasters[opts], png_path dither png_path write_pam_file pam_path, **opts dithers[opts] = png_path end outputs = paths.map.with_index do |path, index| ext = path.extname.delete_prefix ?. name = path.basename(path.extname) out_path = temp_dir / "output.#{index}.#{ext}" send "render_#{ext}", out_path, name: name, background: background, ** do |dither: false, **opts| (dither ? dithers : rasters)[opts] end next out_path, path end safely "saving, please wait..." do outputs.each do |out_path, path| FileUtils.cp out_path, path log_success "created %s" % path rescue SystemCallError raise "couldn't save #{path}" end paths.select do |path| %w[.png .tif .jpg].include? path.extname end.group_by do |path| path.parent / path.basename(path.extname) end.keys.each do |base| write_world_file Pathname("#{base}.wld"), ppi: .fetch(:ppi, Formats::PPI) Pathname("#{base}.prj").write "#{@projection}\n" end if worldfile end end end |
#save ⇒ Object
123 124 125 126 127 128 |
# File 'lib/nswtopo/map.rb', line 123 def save tap do write "map.json", @neatline.to_json write "map.yml", YAML.dump(centre: @centre, dimensions: @dimensions, scale: @scale, rotation: @rotation, layers: @layers) end end |
#te ⇒ Object
175 176 177 |
# File 'lib/nswtopo/map.rb', line 175 def te [0, 0, *@dimensions] end |
#to_metres(mm) ⇒ Object
183 184 185 |
# File 'lib/nswtopo/map.rb', line 183 def to_metres(mm) mm * @scale / 1000.0 end |
#to_mm(metres) ⇒ Object
179 180 181 |
# File 'lib/nswtopo/map.rb', line 179 def to_mm(metres) metres * 1000.0 / @scale end |
#write_pam_file(path, **opts) ⇒ Object
201 202 203 204 205 206 207 |
# File 'lib/nswtopo/map.rb', line 201 def write_pam_file(path, **opts) REXML::Document.new("", raw: %w[SRS], attribute_quote: :quote).add_element("PAMDataset").tap do |pam| pam.add_element("SRS", "dataAxisToSRSAxisMapping" => "1,2").add_text @projection.wkt2 pam.add_element("GeoTransform").add_text geotransform(**opts).join(?,) path.write pam end end |
#write_world_file(path, **opts) ⇒ Object
192 193 194 195 196 197 198 199 |
# File 'lib/nswtopo/map.rb', line 192 def write_world_file(path, **opts) ulx, mm_per_px, _, uly, _, _ = geotransform(**opts) path.open("w") do |file| file.puts mm_per_px, 0, 0, -mm_per_px file.puts ulx + 0.5 * mm_per_px file.puts uly - 0.5 * mm_per_px end end |