[英]Create a geospatial query in java for mongodb
我做我的项目。 它与MongoDB和Java有关。 我需要从 MongoDB 获取多边形数据。
但是,我的查询总是返回没有找到记录。
这是我的java代码:
string coords = "28.56402,79.93652a27.27569,26.16394a42.69404,20.02808a48.61541,51.37207a"
String[] coors = coords.split("a")
final LinkedList<double[]> polygon = new LinkedList<double[]>();
for(int i= 0;i<coors.length;i++)
{
String[] coo = coors[i].split(",");
System.out.println("coors" + i + " : " + coors[i]);
polygon.addLast(new double[]{Double.parseDouble(coo[0]),Double.parseDouble(coo[1])});
}
BasicDBObject query = new BasicDBObject("loc", new BasicDBObject("$within", new BasicDBObject("$polygon", polygon)));
FindIterable<Document> results = this.getMongoCollectionProcessor().queryDocument(query);
MongoCursor<Document> resultsIterator = results.iterator();
这是我的输出查询:
{ "loc" : { "$within" : { "$polygon" : [ [ 28.56402 , 79.93652] , [ 27.27569 , 26.16394] , [ 42.69404 , 20.02808] , [ 48.61541 , 51.37207]]}}}
查询计数为零。
我究竟做错了什么? 你能帮助我吗? 谢谢。
您可以尝试以下查询。
Geopolygon 将数组数组作为坐标。 使用Filters.geoWithinPolygon
辅助方法,因为within
已被弃用。
String coords = "28.56402,79.93652a27.27569,26.16394a42.69404,20.02808a48.61541,51.37207a";
String[] coors = coords.split("a");
final List<List<Double>> polygons = new ArrayList<>();
for(int i= 0;i<coors.length;i++)
{
String[] coo = coors[i].split(",");
System.out.println("coors" + i + " : " + coors[i]);
polygons.add(Arrays.asList(Double.parseDouble(coo[0]),Double.parseDouble(coo[1])));
}
Bson query = Filters.geoWithinPolygon("loc", polygons);
FindIterable<Document> results = this.getMongoCollectionProcessor().queryDocument(query);
MongoCursor<Document> resultsIterator = results.iterator();
预期查询:
{
loc: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [
[
[28.56402, 79.93652],
[27.27569, 26.16394],
[42.69404, 20.02808],
[48.61541, 51.37207]
]
]
}
}
}
}
如果您使用的是mongoTemplate
那么您可以使用geoNear
找出
import org.springframework.data.geo.Point
// ...
Point point = new Point(location.lng, location.lat);
NearQuery nearQuery = NearQuery.near(point).maxDistance(50, Metrics.MILES);
GeoResults<DomainEntity> results = mongoTemplate.geoNear(nearQuery, DomainEntity.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.