]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
gpx insert now works
[rails.git] / lib / osm.rb
1 module OSM
2
3   # This piece of magic reads a GPX with SAX and spits out
4   # lat/lng and stuff
5   #
6   # This would print every latitude value:
7   #
8   # gpx = OSM:GPXImporter.new('somefile.gpx')
9   # gpx.points {|p| puts p['latitude']}
10   
11   require 'time'
12   require 'rexml/parsers/sax2parser'
13   require 'rexml/text'
14
15   class GPXImporter
16     attr_reader :possible_points
17     attr_reader :actual_points
18     attr_reader :tracksegs
19
20     def initialize(filename)
21       @filename = filename
22       @possible_points = 0
23       @actual_points = 0
24       @tracksegs = 0
25     end
26
27     def points
28       file = File.new(@filename)
29       parser = REXML::Parsers::SAX2Parser.new( file )
30
31       lat = -1
32       lon = -1
33       ele = -1
34       date = Time.now();
35       gotlatlon = false
36       gotele = false
37       gotdate = false
38
39       parser.listen( :start_element,  %w{ trkpt }) do |uri,localname,qname,attributes| 
40         lat = attributes['lat'].to_f
41         lon = attributes['lon'].to_f
42         gotlatlon = true
43         @possible_points += 1
44       end
45
46       parser.listen( :characters, %w{ ele } ) do |text|
47         ele = text
48         gotele = true
49       end
50
51       parser.listen( :characters, %w{ time } ) do |text|
52         if text && text != ''
53           date = Time.parse(text)
54           gotdate = true
55         end
56       end
57
58       parser.listen( :end_element, %w{ trkseg } ) do |uri, localname, qname|
59         @tracksegs += 1
60       end
61
62       parser.listen( :end_element, %w{ trkpt } ) do |uri,localname,qname|
63         if gotlatlon && gotdate
64           ele = '0' unless gotele
65           if lat < 90 && lat > -90 && lon > -180 && lon < 180
66             @actual_points += 1
67             yield Hash['latitude' => lat,'longitude' => lon,'timestamp' => date,'altitude' => ele,'segment' => @tracksegs]
68           end
69         end
70         gotlatlon = false
71         gotele = false
72         gotdate = false
73       end
74       parser.parse
75     end
76   end
77 end