使用MongoDB计算Java中的距离 [英] Calculate distance in Java Using MongoDB

查看:889
本文介绍了使用MongoDB计算Java中的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Java和MongoDB中的位置计算。我将纬度和经度传递给方法并从提供的输入中找到最近的位置。我可以从我的主表中获取位置名称,其中包含纬度和经度的所有地标。

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.

我的要求是我希望使用MongoDB获取距离的位置 - 喜欢来自XYZ的4Km。
MongoDB有地理空间查询,我正在研究它。我可以通过使用db.runCommand({geoNear:data,near:[ - 73.9000,40.7000],sphere:true,maxDistance:2500/6378137,distanceMultiplier:6378137})在命令提示符下运行来获得提及的输入。

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}).

我在Java中寻找相同的代码,所以我只能通过纬度和经度并获得距离最近的位置。

I am looking equivalent code in Java, so i can pass latitude and longitude only and get nearest location with distance.

提前致谢。

推荐答案

您可以使用Java驱动程序中DB对象的command方法执行命令。可以在此处找到API文档:
http://api.mongodb.org/java/current/com/mongodb/DB.html#command%28com.mongodb.DBObject%29

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

以下是使用Java驱动程序执行命令的方法:

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

我添加了一些System.out.println语句,因此你可以看到命令文档的样子,以及返回结果的字符串表示。

您可以将num:1添加到命令文档中以将结果限制为1.

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

这在geoNear文档中有说明:
http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-geoNearCommand

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!

这篇关于使用MongoDB计算Java中的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆