RGeo为点要素提供了内置方法,例如从点对象拉取纬度和经度值的getter方法lat()和lon()。不幸的是,这些不能作为setter使用。例如:
point = RGeo::Geographic.spherical_factory(:srid => 4326).point(3,5) // => #<RGeo::Geographic::SphericalPointImpl:0x817e521c "POINT (3.0 5.0)">我可以这样做:
point.lat // => 5.0
point.lon // => 3.0但我不能这样做:
point.lat = 4 // => NoMethodError: undefined method `lat=' for #<RGeo::Geographic::SphericalPointImpl:0x00000104024770>关于如何实现setter方法有什么建议吗?您是在模型中执行此操作,还是扩展要素类?
发布于 2012-11-27 15:13:29
我是RGeo的作者,所以你可以在这个基础上认为这个答案是权威的。
简而言之,请避免这样做。RGeo对象故意没有setter方法,因为它们是不可变的对象。这是因为它们可以被缓存,用作散列键,跨线程使用,等等。一些RGeo计算假设特征对象的值永远不会改变,所以像这样的更改可能会产生意想不到的和不可预测的后果。
如果你真的想要一个“改变”的值,创建一个新的对象。例如:
p1 = my_create_a_point()
p2 = p1.factory.point(p1.lon + 20.0, p2.lat)发布于 2012-11-18 02:29:27
我发现了一些有用的东西,尽管可能会有更优雅的解决方案。
在我的Location模型中,我添加了以下方法:
after_initialize :init
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发布于 2013-05-11 06:22:54
我最终在我的模型中做了这样的事情:
class MyModel < ActiveRecord::Base
attr_accessor :longitude, :latitude
attr_accessible :longitude, :latitude
validates :longitude, numericality: { greater_than_or_equal_to: -180, less_than_or_equal_to: 180 }, allow_blank: true
validates :latitude, numericality: { greater_than_or_equal_to: -90, less_than_or_equal_to: 90 }, allow_blank: true
before_save :update_gps_location
def update_gps_location
if longitude.present? || latitude.present?
long = longitude || self.gps_location.longitude
lat = latitude || self.gps_location.latitude
self.gps_location = RGeo::Geographic.spherical_factory(srid: 4326).point(long, lat)
end
end
end然后,您可以像这样更新位置:
my_model.update_attributes(longitude: -122, latitude: 37)我没有在after_initialize块中加载经度/纬度,因为在我的应用程序中,我们永远不需要读取数据,只需要写入数据即可。不过,您可以轻松地添加这一点。
验证工作归功于this answer。
https://stackoverflow.com/questions/13432860
复制相似问题