Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how store latitude and longitude in mongodb collection? and How to use it with Spring?

i want to find near by location so inserting record like this..

db.locationcol.insert({"location":"phase 8,mohali ,punjab ,india","service":"psychologist","loc":{"lon":76.703347,"lat":30.710459}})

and then executing Query on terminal .

db.runCommand(
{
geoNear: "locationcol",
near: { type: "Point", coordinates: [ 76.720845, 30.712097 ] },
spherical: true,
query: { category: "public" }
})

but it is returning ..

{ "ok" : 0, "errmsg" : "no geo indices for geoNear" }

i am also trying it with Spring ...

public GeoResults getnearby(double longitude,double latitude, String service) {

Point point = new Point(longitude,latitude);

Query query = new Query(Criteria.where("service").is(service));

query.fields().include("service").include("location").include("loc");

NearQuery nearQuery = NearQuery.near(point).maxDistance(new Distance(50, Metrics.KILOMETERS));
nearQuery.query(query);
nearQuery.num(20);

GeoResults<locationcol> data = operations.geoNear(nearQuery, locationcol.class,"locationcol");

return data;
}

this code is returning empty list .i am not getting that where i am going wrong. help !!

like image 701
Deepak Pareek Avatar asked Mar 25 '15 07:03

Deepak Pareek


1 Answers

Before you can execute geospatial queries, you need to create a geospatial index:

db.locationcol.createIndex( { loc : "2dsphere" } )

Also, you need to store your locations as valid GeoJSON objects so MongoDB can parse them properly:

loc : { type: "Point", coordinates: [ -76.703347, 30.710459 ] },
like image 107
Philipp Avatar answered Nov 15 '22 06:11

Philipp