1 class ApiController < ApplicationController
4 before_filter :check_api_readable, :except => [:capabilities]
5 after_filter :compress_output
7 # Help methods for checking boundary sanity and area size
10 #COUNT is the number of map requests to allow before exiting and starting a new process
13 # The maximum area you're allowed to request, in square degrees
14 MAX_REQUEST_AREA = APP_CONFIG['max_request_area']
16 # Number of GPS trace/trackpoints returned per-page
17 TRACEPOINTS_PER_PAGE = APP_CONFIG['tracepoints_per_page']
19 # Get an XML response containing a list of tracepoints that have been uploaded
20 # within the specified bounding box, and in the specified page.
23 #retrieve the page number
24 page = params['page'].to_i
30 report_error("Page number must be greater than or equal to 0")
34 offset = page * TRACEPOINTS_PER_PAGE
38 unless bbox and bbox.count(',') == 3
39 report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
43 bbox = bbox.split(',')
44 min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
45 # check boundary is sane and area within defined
46 # see /config/application.yml
48 check_boundaries(min_lon, min_lat, max_lon, max_lat)
49 rescue Exception => err
50 report_error(err.message)
55 points = Tracepoint.find_by_area(min_lat, min_lon, max_lat, max_lon, :offset => offset, :limit => TRACEPOINTS_PER_PAGE, :order => "timestamp DESC" )
57 doc = XML::Document.new
58 doc.encoding = XML::Encoding::UTF_8
59 root = XML::Node.new 'gpx'
60 root['version'] = '1.0'
61 root['creator'] = 'OpenStreetMap.org'
62 root['xmlns'] = "http://www.topografix.com/GPX/1/0/"
66 track = XML::Node.new 'trk'
69 trkseg = XML::Node.new 'trkseg'
72 points.each do |point|
73 trkseg << point.to_xml_node()
76 #exit when we have too many requests
77 if @@count > MAX_COUNT
78 render :text => doc.to_s, :content_type => "text/xml"
83 response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
85 render :text => doc.to_s, :content_type => "text/xml"
88 # This is probably the most common call of all. It is used for getting the
89 # OSM data for a specified bounding box, usually for editing. First the
90 # bounding box (bbox) is checked to make sure that it is sane. All nodes
91 # are searched, then all the ways that reference those nodes are found.
92 # All Nodes that are referenced by those ways are fetched and added to the list
94 # Then all the relations that reference the already found nodes and ways are
95 # fetched. All the nodes and ways that are referenced by those ways are then
96 # fetched. Finally all the xml is returned.
100 # Figure out the bbox
101 bbox = params['bbox']
103 unless bbox and bbox.count(',') == 3
104 # alternatively: report_error(TEXT['boundary_parameter_required']
105 report_error("The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
109 bbox = bbox.split(',')
111 min_lon, min_lat, max_lon, max_lat = sanitise_boundaries(bbox)
113 # check boundary is sane and area within defined
114 # see /config/application.yml
116 check_boundaries(min_lon, min_lat, max_lon, max_lat)
117 rescue Exception => err
118 report_error(err.message)
122 # FIXME um why is this area using a different order for the lat/lon from above???
123 @nodes = Node.find_by_area(min_lat, min_lon, max_lat, max_lon, :conditions => {:visible => true}, :limit => APP_CONFIG['max_number_of_nodes']+1)
124 # get all the nodes, by tag not yet working, waiting for change from NickB
125 # need to be @nodes (instance var) so tests in /spec can be performed
126 #@nodes = Node.search(bbox, params[:tag])
128 node_ids = @nodes.collect(&:id)
129 if node_ids.length > APP_CONFIG['max_number_of_nodes']
130 report_error("You requested too many nodes (limit is #{APP_CONFIG['max_number_of_nodes']}). Either request a smaller area, or use planet.osm")
133 if node_ids.length == 0
134 render :text => "<osm version='#{API_VERSION}' generator='#{GENERATOR}'></osm>", :content_type => "text/xml"
138 doc = OSM::API.new.get_xml_doc
141 bounds = XML::Node.new 'bounds'
142 bounds['minlat'] = min_lat.to_s
143 bounds['minlon'] = min_lon.to_s
144 bounds['maxlat'] = max_lat.to_s
145 bounds['maxlon'] = max_lon.to_s
149 # find which ways are needed
151 if node_ids.length > 0
152 way_nodes = WayNode.find_all_by_node_id(node_ids)
153 way_ids = way_nodes.collect { |way_node| way_node.id[0] }
154 ways = Way.find(way_ids)
156 list_of_way_nodes = ways.collect { |way|
157 way.way_nodes.collect { |way_node| way_node.node_id }
159 list_of_way_nodes.flatten!
162 list_of_way_nodes = Array.new
165 # - [0] in case some thing links to node 0 which doesn't exist. Shouldn't actually ever happen but it does. FIXME: file a ticket for this
166 nodes_to_fetch = (list_of_way_nodes.uniq - node_ids) - [0]
168 if nodes_to_fetch.length > 0
169 @nodes += Node.find(nodes_to_fetch)
173 user_display_name_cache = {}
175 @nodes.each do |node|
177 doc.root << node.to_xml_node(user_display_name_cache)
178 visible_nodes[node.id] = node
185 doc.root << way.to_xml_node(visible_nodes, user_display_name_cache)
190 relations = Relation.find_for_nodes(visible_nodes.keys, :conditions => {:visible => true}) +
191 Relation.find_for_ways(way_ids, :conditions => {:visible => true})
193 # we do not normally return the "other" partners referenced by an relation,
194 # e.g. if we return a way A that is referenced by relation X, and there's
195 # another way B also referenced, that is not returned. But we do make
196 # an exception for cases where an relation references another *relation*;
197 # in that case we return that as well (but we don't go recursive here)
198 relations += Relation.find_for_relations(relations.collect { |r| r.id }, :conditions => {:visible => true})
200 # this "uniq" may be slightly inefficient; it may be better to first collect and output
201 # all node-related relations, then find the *not yet covered* way-related ones etc.
202 relations.uniq.each do |relation|
203 doc.root << relation.to_xml_node(user_display_name_cache)
206 response.headers["Content-Disposition"] = "attachment; filename=\"map.osm\""
208 render :text => doc.to_s, :content_type => "text/xml"
210 #exit when we have too many requests
211 if @@count > MAX_COUNT
218 # Get a list of the tiles that have changed within a specified time
221 zoom = (params[:zoom] || '12').to_i
223 if params.include?(:start) and params.include?(:end)
224 starttime = Time.parse(params[:start])
225 endtime = Time.parse(params[:end])
227 hours = (params[:hours] || '1').to_i.hours
228 endtime = Time.now.getutc
229 starttime = endtime - hours
232 if zoom >= 1 and zoom <= 16 and
233 endtime > starttime and endtime - starttime <= 24.hours
234 mask = (1 << zoom) - 1
236 tiles = Node.count(:conditions => ["timestamp BETWEEN ? AND ?", starttime, endtime],
237 :group => "maptile_for_point(latitude, longitude, #{zoom})")
239 doc = OSM::API.new.get_xml_doc
240 changes = XML::Node.new 'changes'
241 changes["starttime"] = starttime.xmlschema
242 changes["endtime"] = endtime.xmlschema
244 tiles.each do |tile, count|
245 x = (tile.to_i >> zoom) & mask
248 t = XML::Node.new 'tile'
252 t["changes"] = count.to_s
259 render :text => doc.to_s, :content_type => "text/xml"
261 render :text => "Requested zoom is invalid, or the supplied start is after the end time, or the start duration is more than 24 hours", :status => :bad_request
265 # External apps that use the api are able to query the api to find out some
266 # parameters of the API. It currently returns:
267 # * minimum and maximum API versions that can be used.
268 # * maximum area that can be requested in a bbox request in square degrees
269 # * number of tracepoints that are returned in each tracepoints page
271 doc = OSM::API.new.get_xml_doc
273 api = XML::Node.new 'api'
274 version = XML::Node.new 'version'
275 version['minimum'] = "#{API_VERSION}";
276 version['maximum'] = "#{API_VERSION}";
278 area = XML::Node.new 'area'
279 area['maximum'] = MAX_REQUEST_AREA.to_s;
281 tracepoints = XML::Node.new 'tracepoints'
282 tracepoints['per_page'] = APP_CONFIG['tracepoints_per_page'].to_s
284 waynodes = XML::Node.new 'waynodes'
285 waynodes['maximum'] = APP_CONFIG['max_number_of_way_nodes'].to_s
290 render :text => doc.to_s, :content_type => "text/xml"