I am working on location calculation in Java and MongoDB. I pass latitude and longitude to method and find nearest location from provided input. I am able to get Location name from my master table where i have all landmarks with latitude and longitude.
My requirement is that i want to get location with distance using MongoDB - like 4Km from XYZ .
MongoDB has Geospatial query and i am working on it. I can get mentioned input by running in command prompt by using db.runCommand({ geoNear : "data", near : [-73.9000, 40.7000], spherical : true, maxDistance : 2500/6378137, distanceMultiplier: 6378137}).
I am looking equivalent code in Java, so i can pass latitude and longitude only and get nearest location with distance.
Thanks in advance.
解决方案
You can perform the command with the "command" method of the DB object in the Java Driver. The API documentation may be found here:
http://api.mongodb.org/java/current/com/mongodb/DB.html#command%28com.mongodb.DBObject%29
Here is how the command may be performed using the Java driver:
BasicDBObject myCmd = new BasicDBObject();
myCmd.append("geoNear", "data");
double[] loc = {-73.9000, 40.7000};
myCmd.append("near", loc);
myCmd.append("spherical", true);
myCmd.append("maxDistance", (double)2500/6378137);
myCmd.append("distanceMultiplier", 6378137);
System.out.println(myCmd);
CommandResult myResult = db.command(myCmd);
System.out.println(myResult.toString());
I added some System.out.println statements, so you can see what the command document looks like, and a string representation of the results that are returned.
You can add num : 1 to the command document to limit the results to 1.
myCmd.append("num", 1);
Hopefully this will get you started. Good luck!