问题描述
我使用将地理位置附加到汽车上。 我的卡域类如下所示:
import com.vividsolutions.jts.geom.Point
class Card {
String name
Point location
}
我的程序在Grails中,因此我提供的示例在Groovy中。 我在找到了类似的帖子该帖子并未真正回答关于如何正确指定半径以为半径设置n公里的最重要问题。
这是我计算圆形几何体的方法:
private static Geometry createCircle(double x, double y, final double RADIUS) {
GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
shapeFactory.setNumPoints(1000);
shapeFactory.setCentre(new Coordinate(x, y))
shapeFactory.setSize( (RADIUS * 2)/88.1)
return shapeFactory.createCircle().getBoundary()
}
圆的大小除以88.1,这只是获得大致尺寸的肮脏方法,但仍然是错误的。
我的查询是这样完成的:
double radius = 40
Geometry filter = createCircle(car.location.x, car.location.y, radius)
Session session = sessionFactory.currentSession
Query q = session.createQuery("select c from Car c where within(c.location, ?) = true")
q.setParameter(0, filter, GeometryUserType.TYPE)
q.list()
这工作不是很准确。 该查询返回了一些应该在圆外的汽车。
这是一个例子。 我的中心是汉堡,半径为40公里。 我做了一个谷歌地图可视化。
这是当我设置radius = 40
:
您会看到在左上角仍绘制了一辆位于圆圈外的汽车。 事实并非如此。 在我看来,我用Google地图绘制的圆不等于我在查询代码中绘制的圆的几何形状。
这是当我设置radius = 30
:
您会看到右下角的汽车消失了,这是正确的,但左上角的汽车仍保留在查询中。
当我绘制用createCircle
创建的圆时,得到以下内容(使用getCoordinates()
获取圆的坐标):
如何查询半径40公里内的所有汽车?
1楼
尝试改为计算几何之间的距离。
您可以使用dwithin
函数(请参见 ):
select c from Car c where dwithin(c.location, :geom, :dist) = true
或只是distance
:
select c from Car c where distance(c.location, :geom) < :dist
另外,别忘了将转换距离量度为度(对于WGS84 SRS)。
编辑 :
使用geom虚构圆的中心,这样就不必生成几何图形,只需按距离过滤即可。
PD:在这篇您可以找到有关度和米转换问题的描述
祝好运!。 CHEMA。