Ruby Geocoder 可以在reverse_geocode 调用中仅返回街道名称吗?

2024-02-19

The geocoder http://www.rubygeocoder.com/gem 将在保存时自动反转地理编码,如果该行after_validation :reverse_geocode包含在模型中。不过,这会导致一长串文本被保存为地址 - 格式类似于“街道名称、城市名称、县名称、州名称、邮政编码、国家/地区名称”。

我只对这个特定项目的街道名称感兴趣,所以我想知道是否有办法修改after_validation调用仅保存该信息。

如果我手动进行反向地理编码,我可以访问road结果中的值:

  place = Place.first
  result = Geocoder.search("#{place.latitude},#{place.longitude}")
  street = result[0].data['address']['road']

我可以设置我自己的习惯after_validation就是这样做的,但我不想重复功能,如果geocoder已经提供了这个。

或者,如果有一种完全不同的方式可以将纬度/经度转换为街道名称,我将有兴趣了解它。如果该选项也包含地址号或地址范围就可以了。


您可以通过提供一个块来自定义reverse_geocode方法,该块接受要进行地理编码的对象和Geocoder::Result对象的数组。

reverse_geocoded_by :latitude, :longitude do |obj,results|
  if geo = results.first
    obj.street = geo.address
  end
end

after_validation :reverse_geocode

每个 Geocoder::Result 对象(结果)提供以下数据:

result.latitude - float
result.longitude - float
result.coordinates - array of the above two
result.address - string
result.city - string
result.state - string
result.state_code - string
result.postal_code - string
result.country - string
result.country_code - string

更多信息可以在地理编码文档 https://github.com/alexreisner/geocoder。您甚至可以找到更多可以利用的领域Geocoder::Result object.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby Geocoder 可以在reverse_geocode 调用中仅返回街道名称吗? 的相关文章

随机推荐