hisoka
hisoka

Reputation: 43

Create a geospatial query in java for mongodb

I do my project. It's related to MongoDB and Java. I need to get data which are in polygon from MongoDB.

However, my query always return No records found.

Here is my java code:

 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();

This my output query:

{ "loc" : { "$within" : { "$polygon" : [ [ 28.56402 , 79.93652] , [ 27.27569 , 26.16394] , [ 42.69404 , 20.02808] , [ 48.61541 , 51.37207]]}}}

query count is zero.

What am I doing wrong? Can you help me? Thanks.

Upvotes: 2

Views: 1944

Answers (2)

sendon1982
sendon1982

Reputation: 11234

If you are using mongoTemplate then you can use geoNear Find out

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);

Upvotes: 0

s7vr
s7vr

Reputation: 75924

You can try the below query.

Geopolygon takes array of arrays as coordinates. Use Filters.geoWithinPolygon helper method as within is deprecated.

 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();

Expected Query:

{
    loc: {
        $geoWithin: {
            $geometry: {
                type: "Polygon",
                coordinates: [
                    [
                        [28.56402, 79.93652],
                        [27.27569, 26.16394],
                        [42.69404, 20.02808],
                        [48.61541, 51.37207]
                    ]
                ]
            }
        }
    }
}

Upvotes: 1

Related Questions