如果我提供一个有效的地址,地理编码器gem一直运行得很好。但如果地址无效,则无法进行地理编码。
如果按全址地理编码失败,如何按邮政编码进行地理编码?
geocoded_by :address
after_validation :geocode
def address
[street, city, province, country, postal_code].compact.join(", ")
end有什么想法吗?
谢谢
发布于 2021-02-02 05:35:09
不幸的是,这有点老生常谈,但您必须覆盖geocode方法。下面这样的代码应该能起到作用:
# Override Geocoder's `geocode` method
def geocode
# Initially just call the original method as intended.
super
# Check to see if geocoding failed.
if latitude.blank? && longitude.blank?
# Now manually set the `user_address` key to only `postal_code`, instead of the original value of `address`.
self.class.geocoder_options[:user_address] = postal_code
# Now call the original method again.
super
end
end我可能会开一个PR关于gem的- your问题,很有意思。某种后备选项肯定会非常有用。:-)
发布于 2021-02-02 18:54:22
我最终使用了不同的解决方案。我不确定这是否是处理它的最好方法,但是:
after_validation :geocode_address
def geocode_address
results = Geocoder.search(full_address)
if results.empty?
postal_code_search = Geocoder.search(postal_code)
if !postal_code_search.empty?
lat_long = postal_code_search.first.coordinates
end
else
lat_long = results.first.coordinates
end
if lat_long && !lat_long.empty?
self.latitude = lat_long[0]
self.longitude = lat_long[1]
end
endhttps://stackoverflow.com/questions/65999024
复制相似问题