每次更新地址时更新地理编码的纬度和经度 [英] Update geocode latitude and longitude everytime address is updated
问题描述
我的shop.rb
中有这个:
def geocode_address
if !address_geo.blank?
geo=Geokit::Geocoders::MultiGeocoder.geocode(address_geo)
errors.add(:address, "Could not Geocode address") if !geo.success
self.lat, self.lng = geo.lat,geo.lng if geo.success
end
end
# Checks whether this object has been geocoded or not. Returns the truth
def geocoded?
lat? && lng?
end
在我的shops_controller.rb
中:
def update
@shop = Shop.find(params[:id])
if @shop.update_attributes(params[:shop])
flash[:notice] = "Successfully saved."
redirect_to shop_path(@shop, :type => @shop.shop_type)
else
render :action => :edit
end
end
现在,当用户首次创建条目时,地址将进行地理编码,并将纬度和经度保存到数据库中.
Now when the user first creates the entry, the address is geocoded, with latitude and longitude saved to the database.
但是当用户更新地址时,纬度和经度将不再进行地理编码,因此仍然使用旧的纬度和经度作为第一个保存位置.
But when the user updates the address, the latitude and longitude will not be geocoded anymore, and thus still using the old latitude and longitude which is the first save.
我如何编写以使每次更新条目时都对Rails重新进行地理编码?
How do I write to have Rails re-geocode everytime an entry is update?
我不能只依赖地址,因为geokit中有一个错误,当我尝试根据地址显示多张地图时,只会显示最后一张.
I can't depend on just the address because there is a bug in geokit that when I try to show multiple maps based on address, only the last one is shown.
我正在使用geokit,Gmaps,Google Maps ...
I'm using geokit, Gmaps, Google Maps...
谢谢.
推荐答案
我将其放在模型中:
before_validation_on_update :geocode_address
这篇关于每次更新地址时更新地理编码的纬度和经度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!