我正在尝试使用地理编码器宝石来查找地址和坐标.我希望它与我的PostGIS空间数据库和RGeo gem一起使用,它使用POINT功能而不是分别保存纬度和经度值.所以我尝试使用我的模型将地理编码器查找的结果保存到RGeo POINT功能中:
class Location < ActiveRecord::Base
attr_accessible :latlon, :name, :address
set_rgeo_factory_for_column(:latlon, RGeo::Geographic.spherical_factory(:srid => 4326))
geocoded_by :name_and_address do |obj, results|
if geo = results.first
obj.latlon = Location.rgeo_factory_for_column(:latlon).point(geo.longitude, geo.latitude)
end
end
after_initialize :init
after_validation :geocode
def init
self.latlon ||= Location.rgeo_factory_for_column(:latlon).point(0, 0)
end
def latitude
self.latlon.lat
end
def latitude=(value)
lon = self.latlon.lon
self.latlon = Location.rgeo_factory_for_column(:latlon).point(lon, value)
end
def longitude
self.latlon.lon
end
def longitude=(value)
lat = self.latlon.lat
self.latlon = Location.rgeo_factory_for_column(:latlon).point(value, lat)
end
def name_and_address
"#{self.name}, #{self.address}"
end
end
Run Code Online (Sandbox Code Playgroud)
在Rails控制台中,我现在可以:
test = Location.new(name: "Eiffel …Run Code Online (Sandbox Code Playgroud) RGeo为POINT特征提供内置方法,例如getter方法lat()以及lon()从POINT对象中提取纬度和经度值.不幸的是,这些不适合作为制定者.例如:
point = RGeo::Geographic.spherical_factory(:srid => 4326).point(3,5) // => #<RGeo::Geographic::SphericalPointImpl:0x817e521c "POINT (3.0 5.0)">
Run Code Online (Sandbox Code Playgroud)
我可以做这个:
point.lat // => 5.0
point.lon // => 3.0
Run Code Online (Sandbox Code Playgroud)
但我做不到:
point.lat = 4 // => NoMethodError: undefined method `lat=' for #<RGeo::Geographic::SphericalPointImpl:0x00000104024770>
Run Code Online (Sandbox Code Playgroud)
有关如何实现setter方法的任何建议?你会在模型中扩展还是扩展Feature类?