mongodb near java,使用MongoDB计算Java中的距离

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值