为RGeo Point设置单个坐标

don*_*ski 7 geocoding postgis ruby-on-rails geospatial

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类?

Dan*_*uma 30

我是RGeo的作者,所以你可以在此基础上考虑这个答案的权威性.

简而言之,请避免这样做.RGeo对象故意没有setter方法,因为它们是不可变对象.这样它们可以被缓存,用作散列键,用于跨线程等.一些RGeo计算假设特征对象的值永远不会改变,因此进行这样的更改可能会产生意外和不可预测的后果.

如果您确实需要"已更改"值,请创建一个新对象.例如:

p1 = my_create_a_point()
p2 = p1.factory.point(p1.lon + 20.0, p2.lat)
Run Code Online (Sandbox Code Playgroud)

  • 阅读以"我是图书馆的作者,你问的问题"为开头的答案总是很有趣.太棒了:) (4认同)