Ruby Geocoder 能否在 reverse_geocode 调用中仅返回街道名称? [英] Can Ruby Geocoder return just the street name on reverse_geocode calls?

查看:38
本文介绍了Ruby Geocoder 能否在 reverse_geocode 调用中仅返回街道名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The geocoder gem will automatically reverse geocode on save if the line after_validation :reverse_geocode is included in the model. This results in a long string of text being saved as the address, though - the format is something like "Street Name, City Name, County Name, State Name, Zip Code, Country Name".

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

I'm only interested in the street name for this particular project, so I'm wondering if there's a way to modify the after_validation call to only save that information.

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

If I do the reverse geocoding manually, I can access the road value in the result:

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

我可以设置自己的自定义 after_validation 来做到这一点,但如果 geocoder 已经提供了这一点,我宁愿不重复功能.

I could set up my own custom after_validation that does just this, but I'd rather not duplicate functionality if geocoder already provides this.

或者,如果有一种完全不同的方式可以将纬度/经度转换为街道名称,我会很想知道.如果这个选项也包括地址编号或地址范围就可以了.

Alternatively, if there's an entirely different way that I can convert latitude/longitude to street name I'd be interested in hearing about it. It would be OK if this option included the address number or address range as well.

推荐答案

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

You can customize the reverse_geocode method by providing a block which takes the object to be geocoded and an array of Geocoder::Result objects.

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,提供以下数据:

Every Geocoder::Result object, result, provides the following data:

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

更多信息可以在地理编码文档中找到.您甚至可以找到更多可以从 Geocoder::Result 对象中提取的字段.

More information can be found in the geocode docs. You might even be able to find more fields that you can pull off of the Geocoder::Result object.

这篇关于Ruby Geocoder 能否在 reverse_geocode 调用中仅返回街道名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆