2013-01-20 44 views
0

我正在尝试geocoder gem并希望接受视口结果。访问地理编码结果

作为Ruby的新手,还有更好的方式来访问结果。

result = Geocoder.search("New York, NY").map(&:geometry) 
north_east_lat = result[0]["viewport"]["northeast"]["lat"] 
north_east_lng = result[0]["viewport"]["northeast"]["lng"] 

虽然这确实工作,它看起来丑陋而脆

上使这更好的任何建议?

回答

0

据我所知,geometry数据只是一个简单的Hash。如果您不喜欢在多个级别通过[“key”]访问值的方式,则可以将Hash转换为OpenStruct。

require 'ostruct' 

result = Geocoder.search("New York, NY").first 
# singleton class http://www.devalot.com/articles/2008/09/ruby-singleton 
class << result 
    def ostructic_geometry 
    ostructly_deep self.geometry 
    end 

    private 
    def ostructly_deep(hash) 
     root = OpenStruct.new 

     # http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html#method-i-marshal_load 
     # -- from the user comment at the bottom -- 
     # In the marchal_load() example, the Hash should have symbols as keys: 
     # hash = { :time => Time.now, :title => 'Birthday Party' } 
     load_data = hash.each_pair.inject({}) do |all, (key, value)| 
     value = ostructly_deep(value) if value.is_a?(Hash) 
     all[key.to_sym] = value # keys need to be symbols to load 
     all 
     end 

     root.marshal_load load_data 
     root 
    end 
end 

now_you_can_call_value_from_member_geometry = result.ostructic_geometry 
now_you_can_call_value_from_member_geometry.bounds.northeast.lat # => 40.9152414 
0

看起来不像。 geometry仅在谷歌地图API结果中定义,因为它是一个非常特定于Google的字段:它不仅包含坐标(地理编码器已提取的坐标),还包含不被认为会掉落的location_type,viewportbounds在地理编码器的标准使用案例中:location_type与结果的精确度有关,viewport完全是关于Google如何“推荐”我们在可视地图上显示此结果,而bounds是整个城市/州/ 。虽然每种方法在一个非常特殊的用例中都是相关的,但大多数使用地理编码器的人不需要它们,因此开发人员不会为它们负责,而是直接暴露这些字段。所以,如果你想要一个干净的方式来访问这些领域,你必须自己构建它。

如果您使用的视功能的时候,它可能是值得让自己的Viewport类来表示这个数据,然后手动缠绕表达(如Viewport.from_geometry(result.geometry))或修补自己viewport方法为Geocoder::Result::Google。你的来电。

1

可以使用地理编码器::结果的方法来访问这些数据,例如:

结果[0]。城市 结果[0] .latitud

看到所有的方法与,结果[0]。方法

相关问题