Module: Gmaps4rails

Defined in:
lib/gmaps4rails.rb,
lib/acts_as_gmappable/base.rb,
app/helpers/gmaps4rails/gmaps_helper.rb,
app/controllers/gmaps4rails/gmaps_controller.rb,
lib/rails/generators/gmaps4rails/templates/initializer.rb

Defined Under Namespace

Modules: ActsAsGmappable, GmapsHelper Classes: DirectionInvalidQuery, DirectionNetStatus, DirectionStatus, Engine, GeocodeInvalidQuery, GeocodeNetStatus, GeocodeStatus, GmapsController

Class Method Summary collapse

Class Method Details

.create_json(object) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/acts_as_gmappable/base.rb', line 15

def Gmaps4rails.create_json(object)
  unless object[object.gmaps4rails_options[:lat_column]].blank? && object[object.gmaps4rails_options[:lng_column]].blank?
"{
\"description\": \"#{object.gmaps4rails_infowindow}\", \"title\": \"#{object.gmaps4rails_title}\",
\"longitude\": \"#{object[object.gmaps4rails_options[:lng_column]]}\", \"latitude\": \"#{object[object.gmaps4rails_options[:lat_column]]}\", \"picture\": \"#{object.gmaps4rails_marker_picture['picture']}\", \"width\": \"#{object.gmaps4rails_marker_picture['width']}\", \"height\": \"#{object.gmaps4rails_marker_picture['height']}\"
} ,"
  end
end

.destination(start_end, options = {}, output = "pretty") ⇒ Object

output could be raw, pretty or clean



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
# File 'lib/acts_as_gmappable/base.rb', line 63

def Gmaps4rails.destination(start_end, options={}, output="pretty")
 if start_end["from"].nil? || start_end["to"].empty?
   raise Gmaps4rails::DirectionInvalidQuery, "Origin and destination must be provided in a hash as first argument"
 else #great, we have stuff to work with
   geocoder = "http://maps.googleapis.com/maps/api/directions/json?origin=#{start_end["from"]}&destination=#{start_end["to"]}"
   #if value is an Array, it means it contains the waypoints, otherwise it's chained normally
   dest_options = options.empty? ? "" : "&" + options.map {|k,v| v.is_a?(Array) ? k + "=" + v * ("|") : k + "=" + v }*("&") 
   #send request to the google api to get the directions
   request = geocoder + dest_options + "&sensor=false"
   url = URI.escape(request)
   resp = Net::HTTP.get_response(URI.parse(url))
   #parse result if result received properly
   if resp.is_a?(Net::HTTPSuccess)             
     #parse the json
     parse = Crack::JSON.parse(resp.body)
     #check if google went well
     if parse["status"] == "OK"
      legs = []
      #Each element in the legs array specifies a single leg of the journey from the origin to the destination in the calculated route
      parse["routes"].first["legs"].each do |leg|
        #delete coded polyline elements from legs and store it in polylines to make output cleaner
        polylines = leg["steps"].map {|step| step.delete("polyline")} if output == "pretty" || output == "clean"
        legs << {
                  "duration"  => { "text" => leg["duration"]["text"], "value" => leg["duration"]["value"].to_f },
                  "distance"  => { "text" => leg["distance"]["text"], "value" => leg["distance"]["value"].to_f },
                  "steps"     => leg["steps"]
                }
        if output == "pretty"
          #polylines contain levels data, which are not that useful.
          polylines.map{|poly| poly.delete("levels")}
          #creat valid json from all polylines, this could be directly passed to javascript for display
          json = polylines.map { |poly| {"coded_array" => poly["points"]} }.to_json
          #merge results in legs
          legs.last.merge!({ "polylines" => json })
        end
      end
      return legs
     else #status != OK
       raise Gmaps4rails::DirectionStatus, "The query you passed seems invalid, status was: #{parse["status"]}.
       Request was: #{request}"
     end #end parse status
   else #if not http success
     raise Gmaps4rails::DirectionNetStatus, "The request sent to google was invalid (not http success): #{request}.
     Response was: #{resp}"           
   end #end resp test
 end # end origin + destination exist
end

.filter(data) ⇒ Object



112
113
114
115
# File 'lib/acts_as_gmappable/base.rb', line 112

def Gmaps4rails.filter(data)
  return data if data.is_a?(Numeric) || data.is_a?(TrueClass) || data.is_a?(FalseClass)
  "'#{data}'"
end

.geocode(address) ⇒ Object



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
# File 'lib/acts_as_gmappable/base.rb', line 24

def Gmaps4rails.geocode(address)
 if address.nil? || address.empty?
   raise Gmaps4rails::GeocodeInvalidQuery, "You must provide an address"
 else #coordinates are valid
   geocoder = "http://maps.googleapis.com/maps/api/geocode/json?address="
   output = "&sensor=false"
   #send request to the google api to get the lat/lng
   request = geocoder + address + output
   url = URI.escape(request)
   resp = Net::HTTP.get_response(URI.parse(url))
   #parse result if result received properly
   if resp.is_a?(Net::HTTPSuccess)             
     #parse the json
     parse = Crack::JSON.parse(resp.body)
     #logger.debug "Google geocoding. Address: #{address}. Result: #{resp.body}"
     #check if google went well
     if parse["status"] == "OK"
       array = []
       parse["results"].each do |result|
         array << { 
                    :lat => result["geometry"]["location"]["lat"], 
                    :lng => result["geometry"]["location"]["lng"],
                    :matched_address => result["formatted_address"] 
                   }
       end
       return array
     else #status != OK
       raise Gmaps4rails::GeocodeStatus, "The address you passed seems invalid, status was: #{parse["status"]}.
       Request was: #{request}"
     end #end parse status
     
   else #if not http success
     raise Gmaps4rails::GeocodeNetStatus, "The request sent to google was invalid (not http success): #{request}.
     Response was: #{resp}"           
   end #end resp test
 end # end address valid
end