基本上我要求我的用户输入他们的完整地址。 在我的观察器中,它看起来像:
<%= label_tag('Address') %> <br>
<%= label_tag(:address_unit, 'Unit/Flat/Apartment Number:') %> <%= number_field_tag(:address_unit, current_profile.try(:address_unit)) %> <br>
<strong><%= label_tag(:address_street, 'Street Number and Name:') %></strong> <%= text_field_tag(:address_street, current_profile.try(:address_street)) %> ie 51 Kennedy Street <br>
<strong><%= label_tag(:address_city, 'Suburb/Town/City:') %></strong> <%= text_field_tag(:address_city, current_profile.try(:address_city)) %> <br>
<strong><%= label_tag(:address_state, 'State/Province:') %></strong> <%= text_field_tag(:address_state, current_profile.try(:address_state)) %> <br>
<strong><%= label_tag(:address_zip, 'Post/ZIP Code:') %></strong> <%= text_field_tag(:address_zip, current_profile.try(:address_zip)) %> <br>
<strong><%= label_tag(:address_country, 'Country:') %></strong> <%= text_field_tag(:address_country, current_profile.try(:address_country)) %> <br>
在我的控制器中,我基本上连接这些字段,然后将其传递给geocoder,如:
def address_check
complete_address = ''
if (params[:address_unit])
complete_address += params[:address_unit] + ', '
end
complete_address += params[:address_street] + ', ' + params[:address_city] + ', '\
+ params[:address_state] + ', ' + params[:address_zip] + ', ' + params[:address_country]
coords = Geocoder.coordinates(complete_address)
coord_invalid = coords.present?
return coord_valid ? nil : 'Address cannot be found, please correct your address'
end
此地址检查的目的是确保用户已写入现有地址。我遇到的问题是,只要提供邮政编码和国家/地区,Geocoder就会接受任何地址。例如:asdasd, asdasd, asdasad, 90503, USA
是可接受的地址。
我的问题是,有没有办法精确查找地址,如果找不到,那么没有coords返回?顺便说一下,我使用Rails 4。