cloudmade-wu 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
data/README ADDED
@@ -0,0 +1,27 @@
1
+ CloudMade
2
+ =========
3
+
4
+ CloudMadeAPI is a Ruby API for CloudMade's online services: Geocoding, Routing and Tiles.
5
+
6
+ Full documentation is available online at http://cloudmade.com/developers/docs/
7
+
8
+ Install
9
+ =======
10
+
11
+ Using easy_install
12
+
13
+ gem install cloudmade
14
+
15
+ Testing
16
+ =======
17
+
18
+ To test the source distribution you will need to run following command:
19
+
20
+ rake test
21
+
22
+ Module Documentation
23
+ ====================
24
+
25
+ To generate module documentation you will need to run the following command:
26
+
27
+ rake rdoc
data/Rakefile ADDED
@@ -0,0 +1,41 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'rake/clean'
4
+ require 'rake/gempackagetask'
5
+ require 'rake/rdoctask'
6
+ require 'rake/testtask'
7
+
8
+ spec = Gem::Specification.new do |s|
9
+ s.name = 'cloudmade-wu'
10
+ s.version = '0.1.2'
11
+ s.has_rdoc = true
12
+ s.extra_rdoc_files = ['README', 'LICENSE']
13
+ s.summary = 'Custom CloudMade Ruby API with Route class renamed to avoid conflicts'
14
+ s.description = s.summary
15
+ s.author = 'MarcAliasGus'
16
+ s.email = 'marc_alias_gus@hotmail.com'
17
+ s.homepage = 'https://github.com/MarcAliasGus'
18
+ # s.executables = ['your_executable_here']
19
+ s.files = %w(LICENSE README Rakefile) + Dir.glob("{bin,lib,spec}/**/*")
20
+ s.require_path = "lib"
21
+ s.bindir = "bin"
22
+ end
23
+
24
+ Rake::GemPackageTask.new(spec) do |p|
25
+ p.gem_spec = spec
26
+ p.need_tar = true
27
+ p.need_zip = true
28
+ end
29
+
30
+ Rake::RDocTask.new do |rdoc|
31
+ files =['README', 'LICENSE', 'lib/**/*.rb']
32
+ rdoc.rdoc_files.add(files)
33
+ rdoc.main = "README" # page to start on
34
+ rdoc.title = "CloudMadeAPI Docs"
35
+ rdoc.rdoc_dir = 'doc/rdoc' # rdoc output folder
36
+ rdoc.options << '--line-numbers'
37
+ end
38
+
39
+ Rake::TestTask.new do |t|
40
+ t.test_files = FileList['test/test*.rb']
41
+ end
data/lib/client.rb ADDED
@@ -0,0 +1,86 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ module CloudMade
17
+ class Client
18
+ attr_accessor :connection
19
+ attr_accessor :base_url
20
+ attr_writer :port
21
+ attr_accessor :api_key
22
+ #attr_reader :token
23
+
24
+ #:nodoc:
25
+ def url
26
+ return "#{base_url}#{@port != nil ? ':' + port.to_s : ''}"
27
+ end
28
+
29
+ #:nodoc:
30
+ def port
31
+ return 80 if @port == nil
32
+ @port
33
+ end
34
+
35
+ # Tiles service
36
+ def tiles
37
+ @tiles = TilesService.new(self.connection, 'tile') if @tiles == nil
38
+ return @tiles
39
+ end
40
+
41
+ # Geocoding service
42
+ def geocoding
43
+ @geocoding = GeocodingService.new(self.connection, 'geocoding') if @geocoding == nil
44
+ return @geocoding
45
+ end
46
+
47
+ # Routing service
48
+ def routing
49
+ @routing = RoutingService.new(self.connection, 'routes') if @routing == nil
50
+ return @routing
51
+ end
52
+
53
+ # Locations service
54
+ def locations
55
+ @locations = LocationsService.new(self.connection, '') if @locations == nil
56
+ return @locations
57
+ end
58
+
59
+ class << self
60
+ def from_connection(connection)
61
+ client = Client.new
62
+ client.connection = connection
63
+ return client
64
+ end
65
+
66
+ def from_parameters(api_key, base_url = nil, port = nil)
67
+ client = Client.new
68
+ client.connection = Connection.new(api_key, base_url, port)
69
+ return client
70
+ end
71
+
72
+ # TODO: Create here methods to connect from XML and YAML configuration file
73
+ end
74
+
75
+ protected
76
+ def initialize()
77
+ end
78
+ ### 2. Allow loads configuration from XML, YAML files
79
+ #def initialize(api_key, base_url = 'cloudmade.com', port = nil)
80
+ # @base_url = base_url
81
+ # @port = port
82
+ # @api_key = api_key
83
+ # #@token = token
84
+ #end
85
+ end
86
+ end
data/lib/cloudmade.rb ADDED
@@ -0,0 +1,25 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ require 'rubygems'
17
+ require 'connection'
18
+ require 'client'
19
+ require 'geometry'
20
+ require 'service'
21
+ require 'tiles'
22
+ require 'geocoding'
23
+ require 'routing'
24
+ require 'locations'
25
+ require 'exceptions'
data/lib/connection.rb ADDED
@@ -0,0 +1,70 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ module CloudMade
18
+ # This +Connection+ class provides a connection to CloudMade online services (HTTP API).
19
+ # Normally you don't need to create it directly. Construct a 'Client' from parameters instead.
20
+ #
21
+ # Connection examples:
22
+ #
23
+ # conn = CloudMade::Connection.new('cloudmade.com', 80, 'FAKE_API_KEY')
24
+ # CloudMade.Client.new(conn)
25
+ #
26
+ class Connection
27
+ attr_accessor :base_url
28
+ attr_writer :port
29
+ attr_accessor :api_key
30
+
31
+ # Initializes connection
32
+ # * +base_url+ should not start with 'www'
33
+ # * +port+ integer value of port for CloudMade portal, if nil then default 80 port is used
34
+ # * +api_key+ your API key to connect to CloudMade services
35
+ def initialize(api_key = nil, base_url = 'cloudmade.com', port = nil)
36
+ self.api_key = api_key
37
+ self.base_url = base_url
38
+ self.base_url = 'cloudmade.com' if self.base_url == nil or self.base_url.empty?
39
+ self.port = port
40
+ end
41
+
42
+ # Make a HTTP connection and send a request. Called by the cloudmade 'Client' object internally
43
+ def connect(server_url, request)
44
+ #sputs "#{server_url} #{request}"
45
+ result = nil
46
+ Net::HTTP.start(server_url, self.port) {|http|
47
+ req = Net::HTTP::Get.new("#{request}")
48
+ response = http.request(req)
49
+ case response
50
+ when Net::HTTPSuccess, Net::HTTPRedirection
51
+ result = response.body
52
+ else
53
+ raise HTTPError.new("Couldn't read data. HTTP status: #{response}")
54
+ end
55
+ }
56
+ return result
57
+ end
58
+
59
+ # Convenience method. Return the base URL and port of this Connection
60
+ def url
61
+ return "#{@base_url}#{@port != nil ? ':' + port.to_s : ''}"
62
+ end
63
+
64
+ # Port number of this Connection
65
+ def port
66
+ return 80 if @port == nil
67
+ @port
68
+ end
69
+ end
70
+ end
data/lib/examples.rb ADDED
@@ -0,0 +1,23 @@
1
+ require 'cloudmade'
2
+ include CloudMade
3
+
4
+ cm = CloudMade::Client.from_parameters('BC9A493B41014CAABB98F0471D759707')
5
+
6
+ puts 'Testing CloudMade Client'
7
+ puts "Geocoding"
8
+ puts "---------"
9
+ puts "Find"
10
+ puts cm.geocoding.find('Potsdamer Platz, Berlin, Germany')
11
+ puts "Find closest"
12
+ puts cm.geocoding.find_closest('pub', 51.66117, 13.37654)
13
+
14
+ puts "Routing\n-------\n"
15
+ puts cm.routing.route(
16
+ CloudMade::Point.new(47.25976, 9.58423),
17
+ CloudMade::Point.new(47.66117, 9.99882))
18
+
19
+ puts "Tiles\n-----\n"
20
+ tile = cm.tiles.get_tile(50.39947, 30.6479, 15)
21
+ file = File.new('my_tile.png', 'w')
22
+ file.write(tile)
23
+ file.close
data/lib/exceptions.rb ADDED
@@ -0,0 +1,35 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ #Raised when API key is not specified in Connection constructor
18
+ class APIKeyMissingError < Exception
19
+ end
20
+
21
+ #Raised when object was not found by geocoding service
22
+ class ObjectNotFound < Exception
23
+ end
24
+
25
+ #Raised when HTTP code other than 200 returned
26
+ class HTTPError < Exception
27
+ end
28
+
29
+ #Raised when specified route couldn't be found
30
+ class RouteNotFound < Exception
31
+ end
32
+
33
+ #Raised when geometry is malformed
34
+ class GeometryParseError < Exception
35
+ end
data/lib/geocoding.rb ADDED
@@ -0,0 +1,143 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ module CloudMade
18
+ require 'cgi'
19
+
20
+ # Class that is responsible for geocoding services of Cloudmade
21
+ class GeocodingService < Service
22
+
23
+ # Find objects that match given query. Returns GeoResults object.
24
+ #
25
+ # * +query+ Query by which objects should be searched
26
+ # * +options+ Additional options, contains
27
+ # results: How many results should be returned.
28
+ # skip: Number of results to skip from beginning.
29
+ # bbox: Bounding box in which objects should be searched.
30
+ # bbox_only: If set to False, results will be searched in the whole world if there are no results for a given bbox.
31
+ # return_geometry: If specified, adds geometry in returned results. Defaults to true.
32
+ #
33
+ def find(query, options = {})
34
+ options['results'] = 10 unless options.has_key? 'results'
35
+ options['skip'] = 0 unless options.has_key? 'skip'
36
+ options['bbox_only'] = true unless options.has_key? 'bbox_only'
37
+ options['return_geometry'] = true unless options.has_key? 'return_geometry'
38
+ request = "/find/#{CGI.escape(query)}.js?#{Service.to_url_params(options)}"
39
+ GeoResults.new(JSON.parse(connect request))
40
+ end
41
+
42
+ # Find closest object to a given point.
43
+ # For a list of available object types, see:
44
+ # http://www.cloudmade.com/developers/docs/geocoding-http-api/object_types
45
+ # Returns GeoResult object, that contain found objects.
46
+ # Raise ObjectNotFound: Raised when no object could be found in radius of 50 km from point.
47
+ #
48
+ # * +object_type+ Type of object, that should be searched.
49
+ # * +point+ Closest object to this point will be searched.
50
+ # * +options+ are
51
+ # * +return_geometry+ If specified, adds geometry in returned results. Defaults to true
52
+
53
+ # TODO: Modify lat, lon parameters to point
54
+ def find_closest(object_type, lat, lon, options = {})
55
+ lat_lon = "#{CGI.escape(lon.to_s + '+' + lat.to_s)}"
56
+ request = "/closest/#{object_type}/#{lat_lon}.js?#{Service.to_url_params(options)}"
57
+ geo_results = GeoResults.new(JSON.parse(connect request))
58
+ raise ObjectNotFound.new if (geo_results.results == nil or geo_results.results.size == 0)
59
+ return geo_results.results[0]
60
+ end
61
+
62
+ # :nodoc:
63
+ def url_template
64
+ return "http://#{@subdomain}.#{@connection.url}/#{@connection.api_key}/geocoding"
65
+ end
66
+ end
67
+
68
+ # Location of the object in geographical terms
69
+ class Location
70
+ # road: Road on which object is situated
71
+ attr_accessor :road
72
+ # city: City, where the object is situated
73
+ attr_accessor :city
74
+ # county: County, where the object is situated
75
+ attr_accessor :county
76
+ # country: Country in which the object is situated
77
+ attr_accessor :country
78
+ # postcode: Postcode, which corresponds to location of the object
79
+ attr_accessor :postcode
80
+
81
+ def initialize(data)
82
+ self.road = data['road']
83
+ self.city = data['city']
84
+ self.county = data['county']
85
+ self.country = data['country']
86
+ self.postcode = data['postcode']
87
+ end
88
+ end
89
+
90
+ # Parsed results of geocoding request
91
+ class GeoResults
92
+ # Founded results
93
+ attr_accessor :found
94
+ # List of found GeoResult objects
95
+ attr_accessor :results
96
+ # Bounds of result set
97
+ attr_accessor :bounds
98
+
99
+ def initialize(data)
100
+ self.found = Integer(data['found'])
101
+ if (data['features'] != nil) then
102
+ self.results = data['features'].map { |feature_data| CloudMade::GeoResult.new(feature_data) }
103
+ end
104
+ self.bounds = CloudMade::BBox.from_coordinates(data['bounds']) if data.has_key? 'bounds'
105
+ end
106
+
107
+ def to_s
108
+ results.join(',') if results != nil
109
+ end
110
+ end
111
+
112
+ class GeoResult
113
+ # Id of the object
114
+ attr_accessor :id
115
+ # Geometry of the object
116
+ attr_accessor :geometry
117
+ # Centroid of the object
118
+ attr_accessor :centroid
119
+ # Bounds of result set
120
+ attr_accessor :bounds
121
+ # Properties of the object
122
+ attr_accessor :properties
123
+ # Location of the object
124
+ attr_accessor :location
125
+
126
+ def initialize(data)
127
+ self.id = data['id']
128
+ self.geometry = CloudMade::Geometry.parse(data['geometry'])
129
+ self.centroid = CloudMade::Geometry.parse(data['centroid'])
130
+ self.bounds = CloudMade::BBox.from_coordinates(data['bounds']) if data.has_key? 'bounds'
131
+ self.properties = data['properties']
132
+ if data.has_key? 'location'
133
+ self.location = Location.new(data['location'])
134
+ else
135
+ self.location = nil
136
+ end
137
+ end
138
+
139
+ def to_s
140
+ self.geometry.to_s
141
+ end
142
+ end
143
+ end
data/lib/geometry.rb ADDED
@@ -0,0 +1,139 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ module CloudMade
18
+ class Geometry
19
+
20
+ class << self
21
+ def parse(data)
22
+ return nil if data == nil
23
+ case data['type'].downcase
24
+ when 'point' then return Point.new(data['coordinates'])
25
+ when 'line' then return Line.new(data['coordinates'])
26
+ when 'multilinestring' then return MultiLine.new(data['coordinates'])
27
+ when 'polygon' then return Polygon.new(data['coordinates'])
28
+ when 'multipolygon' then return MultiPolygon.new(data['coordinates'])
29
+ end
30
+ end
31
+ end
32
+ end
33
+
34
+ class Point < Geometry
35
+ attr_accessor :lat
36
+ attr_accessor :lon
37
+
38
+ # Posible initializers are
39
+ # Point.new(1, -1)
40
+ # Point.new([1, -1])
41
+ def initialize(*args)
42
+ if args.size == 1
43
+ @lat = args[0][0]
44
+ @lon = args[0][1]
45
+ elsif args.size == 2
46
+ @lat = args[0]
47
+ @lon = args[1]
48
+ end
49
+ end
50
+
51
+ def ==(point)
52
+ return (point.lat == @lat and point.lon == @lon)
53
+ end
54
+
55
+ def to_s
56
+ "Point(#{@lat},#{@lon})"
57
+ end
58
+
59
+ def to_latlon
60
+ "#{@lat},#{@lon}"
61
+ end
62
+ end
63
+
64
+ class Line < Geometry
65
+ attr_accessor :points
66
+
67
+ def initialize(coords)
68
+ @points = coords.map { |latlng| Point.new(latlng) }
69
+ end
70
+
71
+ def to_s
72
+ "Line(#{@points.join(',')})"
73
+ end
74
+ end
75
+
76
+
77
+ class MultiLine < Geometry
78
+ attr_accessor :lines
79
+
80
+ def initialize(coords)
81
+ @lines = coords.map { |line_coords| Line.new(line_coords) }
82
+ end
83
+
84
+ def to_s
85
+ "MultiLine(#{@lines.join(',')})"
86
+ end
87
+ end
88
+
89
+ class Polygon < Geometry
90
+ attr_accessor :border_line
91
+ attr_accessor :holes
92
+
93
+ def initialize(coords)
94
+ @border_line = Line.new(coords[0])
95
+ @holes = coords.slice(1, coords.length).map { |line_coords| Line.new(line_coords) }
96
+ end
97
+
98
+ def to_s
99
+ "Polygon(#{@border_line} - (#{@holes.join(',')}))"
100
+ end
101
+ end
102
+
103
+ class MultiPolygon < Geometry
104
+ attr_accessor :polygons
105
+
106
+ def initialize(coords)
107
+ @polygons = coords.map { |poly_coords| Polygon.new(poly_coords) }
108
+ end
109
+
110
+ def to_s
111
+ "MultiPolygon(#{@polygons.join(',')})"
112
+ end
113
+ end
114
+
115
+ class BBox < Geometry
116
+ attr_accessor :points
117
+
118
+ def initialize(points)
119
+ self.points = points
120
+ end
121
+
122
+ class << self
123
+ def from_points(points)
124
+ return BBox.new(points)
125
+ end
126
+
127
+ def from_coordinates(coords)
128
+ point1 = Point.new(coords[0][0], coords[0][1])
129
+ point2 = Point.new(coords[1][0], coords[1][1])
130
+ return BBox.new([point1, point2])
131
+ end
132
+ end
133
+
134
+ def ==(bbox)
135
+ return (bbox.points[0] == self.points[0] and bbox.points[1] = self.points[1] or
136
+ bbox.points[0] == self.points[1] and bbox.points[1] = self.points[0])
137
+ end
138
+ end
139
+ end
data/lib/locations.rb ADDED
@@ -0,0 +1,20 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ module CloudMade
18
+ class LocationsService < Service
19
+ end
20
+ end
data/lib/routing.rb ADDED
@@ -0,0 +1,145 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ require 'cgi'
18
+ require 'json'
19
+
20
+ module CloudMade
21
+
22
+ #Class corresponding for CloudMade's routing service
23
+ class RoutingService < Service
24
+
25
+ ROUTE_TYPES = ['car', 'foot', 'bicycle']
26
+ OUTPUT_FORMATS = ['js', 'json', 'gpx']
27
+ STATUS_OK = 0
28
+ STATUS_ERROR = 1
29
+ EARTHS_DIRECTIONS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
30
+ TURN_TYPE = ["C", "TL", "TSLL", "TSHL", "TR", "TSLR", "TSHR", "U"]
31
+
32
+ # Build route. Returns route that was found, instance of CloudMade::Route2
33
+ # * +start_point+ Starting point
34
+ # * +end_point+ Ending point
35
+ # * +route_type+ Type of route, e.g. 'car', 'foot', etc.
36
+ # * +transit_points+ List of points route must visit before
37
+ # reaching end. Points are visited in the same order they are
38
+ # specified in the sequence.
39
+ # * +route_type_modifier+ Modifier of the route type
40
+ # * +lang+ Language code in conformance to `ISO 3166-1 alpha-2` standard
41
+ # * +units+ Measure units for distance calculation
42
+ def route(start_point, end_point, transit_points = nil, route_type = 'car', lang = 'en', route_type_modifier = nil)
43
+ transit_points = ",[#{transit_points.map {|point| point.to_latlon}.join(',')}]" if not transit_points == nil
44
+ route_type_modifier = "/#{route_type_modifier}" if not route_type_modifier == nil
45
+ url = "/#{start_point.to_latlon}#{transit_points},#{end_point.to_latlon}/#{route_type}#{route_type_modifier}.js?lang=#{lang}&units=km"
46
+ return CMRoute.new(JSON.parse(connect url))
47
+ end
48
+
49
+ #:nodoc:
50
+ def url_template
51
+ return "http://#{@subdomain}.#{@connection.url}/#{@connection.api_key}/api/0.3"
52
+ end
53
+ end
54
+
55
+
56
+ # Statistics of the route
57
+ class RouteSummary
58
+ attr_accessor :total_distance
59
+ attr_accessor :total_time
60
+ attr_accessor :start_point
61
+ attr_accessor :end_point
62
+ attr_accessor :transit_points
63
+
64
+ def initialize(summary)
65
+ self.total_distance = Float(summary['total_distance'])
66
+ self.total_time = Float(summary['total_time'])
67
+ self.start_point = summary['start_point']
68
+ self.end_point = summary['end_point']
69
+ self.transit_points = summary['transit_points']
70
+ end
71
+ end
72
+
73
+ # Wrapper around raw data being returned by routing service
74
+ class CMRoute
75
+
76
+ # List of route instructions
77
+ attr_accessor :instructions
78
+ # Statistical info about the route
79
+ attr_accessor :summary
80
+ # Geometry of route
81
+ attr_accessor :geometry
82
+ #Version of routing HTTP API
83
+ attr_accessor :version
84
+ # Status of response
85
+ attr_accessor :status
86
+ attr_accessor :status_message
87
+
88
+ STATUS_OK = 0
89
+ STATUS_ERROR = 1
90
+
91
+ def initialize(data)
92
+ begin
93
+ self.status = data['status'].to_i
94
+ self.instructions = data['route_instructions'].map { |instruction_data| RouteInstruction.new(instruction_data) }
95
+ self.summary = RouteSummary.new(data['route_summary'])
96
+ self.geometry = Line.new(data['route_geometry'])
97
+ self.version = data['version']
98
+ self.status_message = data['status_message']
99
+ rescue
100
+ raise RouteNotFound
101
+ end
102
+ end
103
+
104
+ def to_s
105
+ self.instructions.to_s
106
+ end
107
+ end
108
+
109
+ # Instructions on route passing
110
+ class RouteInstruction
111
+
112
+ # Text instruction
113
+ attr_reader :instruction
114
+ # Length of the segment in meters
115
+ attr_reader :length
116
+ # Index of the first point of the segment
117
+ attr_reader :position
118
+ # Estimated time required to travel the segment in seconds
119
+ attr_reader :time
120
+ # Length of the segments in specified units
121
+ attr_reader :length_caption
122
+ # Earth direction
123
+ attr_reader :earth_direction
124
+ # North-based azimuth
125
+ attr_reader :azimuth
126
+ # Code of the turn type
127
+ attr_reader :turn_type
128
+ # Angle in degress of the turn between two segments
129
+ attr_reader :turn_angle
130
+
131
+ def initialize(data)
132
+ @instruction = data[0]
133
+ @length = Float(data[1])
134
+ @position = Integer(data[2])
135
+ @time = Integer(data[3])
136
+ @length_caption = data[4]
137
+ @earth_direction = data[5]
138
+ @azimuth = Float(data[6])
139
+ if data.length == 9
140
+ @turn_type = data[7]
141
+ @turn_angle = data[8]
142
+ end
143
+ end
144
+ end
145
+ end
data/lib/service.rb ADDED
@@ -0,0 +1,53 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ module CloudMade
18
+
19
+ # General class for all CloudMade's services
20
+ class Service
21
+ require 'net/http'
22
+ require 'cgi'
23
+ attr_accessor :subdomain
24
+ attr_accessor :connection
25
+
26
+ def url_template
27
+ return "http://#{@subdomain}.#{@connection.url}/#{@connection.api_key}"
28
+ end
29
+
30
+ # Template for service's domain
31
+ # By default it is <service_name>.cloudmade.com
32
+ # E.g. tile.cloudmade.com, geocoding.cloudmade.com
33
+ def url
34
+ "#{@subdomain}.#{@connection.base_url}"
35
+ end
36
+
37
+ class << self
38
+ def to_url_params(params)
39
+ params.map {|k,v| "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}" }.join('&')
40
+ end
41
+ end
42
+
43
+ protected
44
+ def initialize(connection, subdomain)
45
+ self.connection = connection
46
+ self.subdomain = subdomain
47
+ end
48
+
49
+ def connect(request)
50
+ return @connection.connect(url, "#{url_template}#{request}")
51
+ end
52
+ end
53
+ end
data/lib/tiles.rb ADDED
@@ -0,0 +1,105 @@
1
+ #
2
+ # Copyright 2009 CloudMade.
3
+ #
4
+ # Licensed under the GNU Lesser General Public License, Version 3.0;
5
+ # You may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.gnu.org/licenses/lgpl-3.0.txt
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ include CloudMade
18
+
19
+ module CloudMade
20
+
21
+ # Class that is responsible for tile services of Cloudmade
22
+ class TilesService < Service
23
+ attr_accessor :default_tile_size
24
+ attr_accessor :default_style_id
25
+
26
+ def initialize(client, subdomain, options = {})
27
+ super(client, subdomain)
28
+ @default_tile_size = (options.has_key? 'tile_size') ? options['tile_size'] : 256
29
+ @default_style_id = (options.has_key? 'style_id') ? options['style_id'] : 1
30
+ end
31
+
32
+ # Convert latitude, longitude pair to tile coordinates. Returns tile coordinates as a CloudMade::Point object
33
+ # * +lat+ Latitude
34
+ # * +lon+ Longitude
35
+ # * +zoom+ Zoom level
36
+ def latlon2tilenums(lat, lon, zoom)
37
+ factor = 2**(zoom - 1)
38
+ lat = radians(lat)
39
+ lon = radians(lon)
40
+ xtile = 1 + lon / Math::PI
41
+ ytile = 1 - Math.log(Math.tan(lat) + (1 / Math.cos(lat))) / Math::PI
42
+ return Point.new((xtile * factor).to_i, (ytile * factor).to_i)
43
+ end
44
+
45
+ # Convert tile coordinates pair to latitude, longitude. Returns latitude, longitude as a CloudMade::Point object
46
+ # * +xtile+ X coordinate of the tile
47
+ # * +ytile+ Y coordinate of the tile
48
+ # * +zoom+ Zoom level
49
+ def tilenums2latlon(xtile, ytile, zoom)
50
+ factor = 2.0 ** zoom
51
+ lon = (xtile * 360 / factor) - 180.0
52
+ lat = Math.atan(Math.sinh(Math::PI * (1 - 2 * ytile / factor)))
53
+ return Point.new(degrees(lat), lon)
54
+ end
55
+
56
+ # :nodoc:
57
+ def radians(degrees)
58
+ Math::PI * degrees / 180
59
+ end
60
+
61
+ def degrees(radians)
62
+ radians * 180 / Math::PI
63
+ end
64
+
65
+ def xtile(lon, zoom)
66
+ factor = 2**(zoom - 1)
67
+ xtile = 1 + lon / 180.0
68
+ return (xtile * factor).to_i
69
+ end
70
+
71
+ def ytile(lat, zoom)
72
+ factor = 2**(zoom - 1)
73
+ lat = radians(lat)
74
+ ytile = 1 - Math.log(Math.tan(lat) + (1 / Math.cos(lat))) / Math::PI
75
+ return (ytile * factor).to_i
76
+ end
77
+
78
+ # Get tile with given latitude, longitude and zoom.
79
+ # Returns Raw PNG data which could be saved to file
80
+ #
81
+ # * +lat+ Latitude of requested tile
82
+ # * +lon+ Longitude of requested tile
83
+ # * +zoom+ Zoom level, on which tile is being requested
84
+ # * +style_id+ CloudMade's style id, if not given, default style is used (usually 1)
85
+ # * +tile_size+ size of tile, if not given the default 256 is used
86
+ def get_tile(lat, lon, zoom, style_id = nil, tile_size = nil)
87
+ get_xy_tile(xtile(lon, zoom), ytile(lat, zoom), zoom, style_id, tile_size)
88
+ end
89
+
90
+ # Get tile with given x, y numbers and zoom
91
+ # Returns Raw PNG data which could be saved to file
92
+ #
93
+ # * +xtile+
94
+ # * +ytile+
95
+ # * +zoom+ Zoom level, on which tile is being requested
96
+ # * +style_id+ CloudMade's style id, if not given, default style is used (usually 1)
97
+ # * +tile_size+ size of tile, if not given the default 256 is used
98
+ def get_xy_tile(xtile, ytile, zoom, style_id = nil, tile_size = nil)
99
+ style_id = self.default_style_id if style_id == nil
100
+ tile_size = self.default_tile_size if tile_size == nil
101
+ connect "/#{style_id}/#{tile_size}/#{zoom}/#{xtile}/#{ytile}.png"
102
+ end
103
+ end
104
+
105
+ end
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cloudmade-wu
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - MarcAliasGus
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-11-23 00:00:00.000000000 Z
13
+ dependencies: []
14
+ description: Custom CloudMade Ruby API with Route class renamed to avoid conflicts
15
+ email: marc_alias_gus@hotmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files:
19
+ - README
20
+ - LICENSE
21
+ files:
22
+ - LICENSE
23
+ - README
24
+ - Rakefile
25
+ - lib/client.rb
26
+ - lib/cloudmade.rb
27
+ - lib/connection.rb
28
+ - lib/examples.rb
29
+ - lib/exceptions.rb
30
+ - lib/geocoding.rb
31
+ - lib/geometry.rb
32
+ - lib/locations.rb
33
+ - lib/routing.rb
34
+ - lib/service.rb
35
+ - lib/tiles.rb
36
+ homepage: https://github.com/MarcAliasGus
37
+ licenses: []
38
+ post_install_message:
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ none: false
44
+ requirements:
45
+ - - ! '>='
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubyforge_project:
56
+ rubygems_version: 1.8.24
57
+ signing_key:
58
+ specification_version: 3
59
+ summary: Custom CloudMade Ruby API with Route class renamed to avoid conflicts
60
+ test_files: []