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);
This is noted in the geoNear documentation: http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-geoNearCommand
Hopefully this will get you started. Good luck!
There is a Java API available that let's you interact with it. The driver has a "command" method that does what you want.
Be sure to read the posted tutorial on the Java driver and how to translate shell commands into Java.
来源:https://stackoverflow.com/questions/10224364/calculate-distance-in-java-using-mongodb