]> git.openstreetmap.org Git - rails.git/blob - lib/osm.rb
e0e83845ea4b33ece2dda45f0c0ff3368d73feee
[rails.git] / lib / osm.rb
1 # The OSM module provides support functions for OSM.
2 module OSM
3
4   require 'time'
5   require 'rexml/parsers/sax2parser'
6   require 'rexml/text'
7   require 'xml/libxml'
8   require 'digest/md5'
9   require 'RMagick'
10
11   # The base class for API Errors.
12   class APIError < RuntimeError
13     def render_opts
14       { :text => "", :status => :internal_server_error }
15     end
16   end
17
18   # Raised when an API object is not found.
19   class APINotFoundError < APIError
20   end
21
22   # Raised when a precondition to an API action fails sanity check.
23   class APIPreconditionFailedError < APIError
24     def render_opts
25       { :text => "", :status => :precondition_failed }
26     end
27   end
28
29   # Raised when to delete an already-deleted object.
30   class APIAlreadyDeletedError < APIError
31     def render_opts
32       { :text => "", :status => :gone }
33     end
34   end
35
36   # Raised when the user logged in isn't the same as the changeset
37   class APIUserChangesetMismatchError < APIError
38     def render_opts
39       { :text => "The user doesn't own that changeset", :status => :conflict }
40     end
41   end
42
43   # Raised when the changeset provided is already closed
44   class APIChangesetAlreadyClosedError < APIError
45     def render_opts
46       { :text => "The supplied changeset has already been closed", :status => :conflict }
47     end
48   end
49
50   # Raised when the provided version is not equal to the latest in the db.
51   class APIVersionMismatchError < APIError
52     def initialize(provided, latest)
53       @provided, @latest = provided, latest
54     end
55
56     attr_reader :provided, :latest
57
58     def render_opts
59       { :text => "Version mismatch: Provided " + provided.to_s +
60       ", server had: " + latest.to_s, :status => :conflict }
61     end
62   end
63
64   # Helper methods for going to/from mercator and lat/lng.
65   class Mercator
66     include Math
67
68     #init me with your bounding box and the size of your image
69     def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
70       xsize = xsheet(max_lon) - xsheet(min_lon)
71       ysize = ysheet(max_lat) - ysheet(min_lat)
72       xscale = xsize / width
73       yscale = ysize / height
74       scale = [xscale, yscale].max
75
76       xpad = width * scale - xsize
77       ypad = height * scale - ysize
78
79       @width = width
80       @height = height
81
82       @tx = xsheet(min_lon) - xpad / 2
83       @ty = ysheet(min_lat) - ypad / 2
84
85       @bx = xsheet(max_lon) + xpad / 2
86       @by = ysheet(max_lat) + ypad / 2
87     end
88
89     #the following two functions will give you the x/y on the entire sheet
90
91     def ysheet(lat)
92       log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
93     end
94
95     def xsheet(lon)
96       lon
97     end
98
99     #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
100
101     def y(lat)
102       return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
103     end
104
105     def x(lon)
106       return  ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
107     end
108   end
109
110   class GreatCircle
111     include Math
112
113     # initialise with a base position
114     def initialize(lat, lon)
115       @lat = lat * PI / 180
116       @lon = lon * PI / 180
117     end
118
119     # get the distance from the base position to a given position
120     def distance(lat, lon)
121       lat = lat * PI / 180
122       lon = lon * PI / 180
123       return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
124     end
125
126     # get the worst case bounds for a given radius from the base position
127     def bounds(radius)
128       latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
129       lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
130       minlat = (@lat - latradius) * 180 / PI
131       maxlat = (@lat + latradius) * 180 / PI
132       minlon = (@lon - lonradius) * 180 / PI
133       maxlon = (@lon + lonradius) * 180 / PI
134       return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
135     end
136   end
137
138   class GeoRSS
139     def initialize(feed_title='OpenStreetMap GPS Traces', feed_description='OpenStreetMap GPS Traces', feed_url='http://www.openstreetmap.org/traces/')
140       @doc = XML::Document.new
141       @doc.encoding = 'UTF-8' 
142
143       rss = XML::Node.new 'rss'
144       @doc.root = rss
145       rss['version'] = "2.0"
146       rss['xmlns:geo'] = "http://www.w3.org/2003/01/geo/wgs84_pos#"
147       @channel = XML::Node.new 'channel'
148       rss << @channel
149       title = XML::Node.new 'title'
150       title <<  feed_title
151       @channel << title
152       description_el = XML::Node.new 'description'
153       @channel << description_el
154
155       description_el << feed_description
156       link = XML::Node.new 'link'
157       link << feed_url
158       @channel << link
159       image = XML::Node.new 'image'
160       @channel << image
161       url = XML::Node.new 'url'
162       url << 'http://www.openstreetmap.org/images/mag_map-rss2.0.png'
163       image << url
164       title = XML::Node.new 'title'
165       title << "OpenStreetMap"
166       image << title
167       width = XML::Node.new 'width'
168       width << '100'
169       image << width
170       height = XML::Node.new 'height'
171       height << '100'
172       image << height
173       link = XML::Node.new 'link'
174       link << feed_url
175       image << link
176     end
177
178     def add(latitude=0, longitude=0, title_text='dummy title', author_text='anonymous', url='http://www.example.com/', description_text='dummy description', timestamp=DateTime.now)
179       item = XML::Node.new 'item'
180
181       title = XML::Node.new 'title'
182       item << title
183       title << title_text
184       link = XML::Node.new 'link'
185       link << url
186       item << link
187
188       guid = XML::Node.new 'guid'
189       guid << url
190       item << guid
191
192       description = XML::Node.new 'description'
193       description << description_text
194       item << description
195
196       author = XML::Node.new 'author'
197       author << author_text
198       item << author
199
200       pubDate = XML::Node.new 'pubDate'
201       pubDate << timestamp.to_s(:rfc822)
202       item << pubDate
203
204       if latitude
205         lat_el = XML::Node.new 'geo:lat'
206         lat_el << latitude.to_s
207         item << lat_el
208       end
209
210       if longitude
211         lon_el = XML::Node.new 'geo:long'
212         lon_el << longitude.to_s
213         item << lon_el
214       end
215
216       @channel << item
217     end
218
219     def to_s
220       return @doc.to_s
221     end
222   end
223
224   class API
225     def get_xml_doc
226       doc = XML::Document.new
227       doc.encoding = 'UTF-8' 
228       root = XML::Node.new 'osm'
229       root['version'] = API_VERSION
230       root['generator'] = 'OpenStreetMap server'
231       doc.root = root
232       return doc
233     end
234   end
235
236   def self.IPLocation(ip_address)
237     Timeout::timeout(4) do
238       Net::HTTP.start('api.hostip.info') do |http|
239         country = http.get("/country.php?ip=#{ip_address}").body
240         country = "GB" if country == "UK"
241         Net::HTTP.start('ws.geonames.org') do |http|
242           xml = REXML::Document.new(http.get("/countryInfo?country=#{country}").body)
243           xml.elements.each("geonames/country") do |ele|
244             minlon = ele.get_text("bBoxWest").to_s
245             minlat = ele.get_text("bBoxSouth").to_s
246             maxlon = ele.get_text("bBoxEast").to_s
247             maxlat = ele.get_text("bBoxNorth").to_s
248             return { :minlon => minlon, :minlat => minlat, :maxlon => maxlon, :maxlat => maxlat }
249           end
250         end
251       end
252     end
253
254     return nil
255   rescue Exception
256     return nil
257   end
258
259   # Construct a random token of a given length
260   def self.make_token(length = 30)
261     chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
262     token = ''
263
264     length.times do
265       token += chars[(rand * chars.length).to_i].chr
266     end
267
268     return token
269   end
270
271   # Return an encrypted version of a password
272   def self.encrypt_password(password, salt)
273     return Digest::MD5.hexdigest(password) if salt.nil?
274     return Digest::MD5.hexdigest(salt + password)
275   end
276
277   # Return an SQL fragment to select a given area of the globe
278   def self.sql_for_area(minlat, minlon, maxlat, maxlon, prefix = nil)
279     tilesql = QuadTile.sql_for_area(minlat, minlon, maxlat, maxlon, prefix)
280     minlat = (minlat * 10000000).round
281     minlon = (minlon * 10000000).round
282     maxlat = (maxlat * 10000000).round
283     maxlon = (maxlon * 10000000).round
284
285     return "#{tilesql} AND #{prefix}latitude BETWEEN #{minlat} AND #{maxlat} AND #{prefix}longitude BETWEEN #{minlon} AND #{maxlon}"
286   end
287
288
289 end