MongoDB地理位置检索

一、查询当前坐标附近的目标

 @Testpublic  void  queryNear(){//1.以当前位置的经纬度为圆点GeoJsonPoint point = new GeoJsonPoint(116.404, 39.915);//2.设置查询的范围,作为半径Distance distance = new Distance(1,Metrics.KILOMETERS);//距离,距离的参数//3.画圆Circle circle = new Circle(point, distance);//4.查询Criteria criteria = Criteria.where("location").withinSphere(circle);Query query = Query.query(criteria);List<Places> places = mongoTemplate.find(query, Places.class);//打印观察for (Places place : places) {System.out.println(place);}}

二、查询并获取距离

/*** 查询附近并得到间距*/@Testpublic  void  queryNearAndGetDistance() {//1.以当前位置的经纬度为圆点GeoJsonPoint geoJsonPoint = new GeoJsonPoint(116.404, 39.915);//2.构造nearQuery对象NearQuery nearQuery = NearQuery.near(geoJsonPoint, Metrics.KILOMETERS).maxDistance(1, Metrics.KILOMETERS);//3、调用mongoTemplate的geoNear方法查询GeoResults<Places> places = mongoTemplate.geoNear(nearQuery, Places.class);for (GeoResult<Places> place : places) {@NonNull Places content = place.getContent();String address = content.getAddress();double value = place.getDistance().getValue();System.out.println(address+ "  距离故宫  "+ value+Metrics.KILOMETERS);}}/*** 北京市东城区南池子大街85号   距离故宫  0.5194875751391679 km* 北京市西城区南长街38号  距离故宫  0.6557599573197416 km* 西城区南长街20号  距离故宫  0.7784741257920857 km* 北京市东城区南池子大街11号   距离故宫  0.7912036177839368 km* 南河沿大街41号(近东华门、长安街)  距离故宫  0.8241175234892675 km* 北京市东城区东华门大街91号  距离故宫  0.8714975354225662 km* 北京市东城区东华门大街37号   距离故宫  0.9868264885628618 km*/

三、探花搜附近的功能之上报地理位置信息

Mongo只能可以进行地理位置搜索,地理位置如何采集?

答案:移动端定位,将地理坐标发送到服务器

1、BaiDuController

package com.tanhua.server.controller;import com.tanhua.server.service.BaiduService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Map;@RestController
@RequestMapping("/baidu")
public class BaiduController {@Autowiredprivate BaiduService baiduService;/*** 上报、更新地理位置位置* 请求路径:/baidu/location     * 请求方式:post* 请求参数:number latitude(纬度), number longitude(经度),String addrStr(位置描述)*/@PostMapping("/location")public ResponseEntity updateLocation(@RequestBody Map param) {Double longitude = Double.valueOf(param.get("longitude").toString());Double latitude = Double.valueOf(param.get("latitude").toString());String address = param.get("addrStr").toString();this.baiduService.saveAndUpdateLocation(longitude, latitude,address);return ResponseEntity.ok(null);}
}

2、BaiDuService

package com.tanhua.server.service;import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.ThreadLocalUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;@Service
public class BaiduService {@DubboReferenceprivate UserLocationApi userLocationApi;/*** 上报地理位置* @param longitude 经度* @param latitude  纬度* @param address*/public void saveAndUpdateLocation(Double longitude, Double latitude, String address) {Long userId = ThreadLocalUtils.getUserId();Boolean result = userLocationApi.saveAndUpdateLocation(userId,longitude,latitude,address);if(!result){throw new BusinessException(ErrorResult.error());}}}

3.UserLacitonApiImpl

if (userLocation == null) {//用户第一次上报地理信息,保存数据到数据库表UserLocation locationInfo = new UserLocation();locationInfo.setUserId(userId);locationInfo.setAddress(address);locationInfo.setCreated(System.currentTimeMillis());locationInfo.setUpdated(System.currentTimeMillis());locationInfo.setLastUpdated(System.currentTimeMillis());locationInfo.setLocation(new GeoJsonPoint(longitude, latitude));mongoTemplate.save(locationInfo);} else {//数据库已有过用户上传的地理信息,更新Update update = Update.update("location", new GeoJsonPoint(longitude, latitude)).set("address", address).set("updated", System.currentTimeMillis()).set("lastUpdated", userLocation.getUpdated());mongoTemplate.updateFirst(query, update, UserLocation.class);}return true;} catch (Exception e) {e.printStackTrace();return false;}}

四、搜附近

vo对象

package com.tanhua.model.vo;import com.tanhua.model.domain.UserInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;//附近的人vo对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class NearUserVo {private Long userId;private String avatar;private String nickname;public static NearUserVo init(UserInfo userInfo) {NearUserVo vo = new NearUserVo();vo.setUserId(userInfo.getId());vo.setAvatar(userInfo.getAvatar());vo.setNickname(userInfo.getNickname());return vo;}
}

TanHuaController

/*** 搜附近* 请求路径:/tanhua/search* 请求方式:get* 请求参数:String  gender(性别),String distance(搜索的范围)*/@GetMapping("/search")public ResponseEntity<List<NearUserVo>> queryNearUser(String gender,@RequestParam(defaultValue = "2000") String distance) {List<NearUserVo> list = tanHuaService.queryNearUser(gender, distance);return ResponseEntity.ok(list);}

TanHuaService

/****搜附近*/public List<NearUserVo> queryNearUser(String gender, String distance) {//1.调用api,查询附近的人,获取他们的idLong userId = ThreadLocalUtils.getUserId();List<Long> userIds =  userLocationApi.queryNearUser(userId,Double.valueOf(distance));//2.判断集合是否为空if(CollUtil.isEmpty(userIds)){return new ArrayList<>();}//3.根据用户id查询用户详情UserInfo userInfo = new UserInfo();userInfo.setGender(gender);Map<Long, UserInfo> userInfoMap = userInfoApi.batchQueryUserInfo(userIds, userInfo);List<NearUserVo> vos = new ArrayList<>();for (Long id : userIds) {if(id == ThreadLocalUtils.getUserId()){continue;//排除自己的id}UserInfo userInfo1 = userInfoMap.get(id);if(userInfo1 != null){NearUserVo vo = NearUserVo.init(userInfo);vos.add(vo);}}return vos;}

UserLocationImpl

 /***搜附近*/public List<Long> queryNearUser(Long userId, Double metre) {//1.获取当前用户地理位置信息,以此为圆点Criteria criteria = Criteria.where("userId").is(userId);Query query = Query.query(criteria);UserLocation location = mongoTemplate.findOne(query, UserLocation.class);GeoJsonPoint point = location.getLocation();//圆点//2.半径Distance distance = new Distance(metre/1000, Metrics.KILOMETERS);//3.画圆Circle circle = new Circle(point, distance);Criteria criteria1 = Criteria.where("location").withinSphere(circle);Query query1 = Query.query(criteria1);List<UserLocation> locationInfos = mongoTemplate.find(query1, UserLocation.class);List<Long> userIds = CollUtil.getFieldValues(locationInfos, "userId", Long.class);return userIds;}

23.MongoDB地理位置检索相关推荐

  1. mongoDB地理位置检索

    查询附近 @Test public void testNear() {//构造坐标点GeoJsonPoint point = new GeoJsonPoint(116.404, 39.915);//构 ...

  2. 七(7)探花功能-MongoDB地理位置查询-附近的人

    课程总结 1.探花功能 业务需求 执行过程 2.MongoDB的地理位置查询 地理位置查询的应用场景 查询案例 3.搜附近 上报地理位置 使用MongoDB搜索附近 一. 探花左划右滑 探花功能是将推 ...

  3. 使用GeocodeService进行地理位置检索

    转载自 http://beniao.cnblogs.com/作      者:Beniao         WebGIS开发群:75662563 Bing Maps进阶系列二:使用GeocodeSer ...

  4. 基于GeoHash算法的地理位置检索

    地理位置检索服务在日常生活中随处可见,小到共享单车.高德地图,大到飞行航线轨迹.上述服务中很多相关功能都可以通过GeoHash来实现,Lucene/Solr中也有应用到GeoHash,通过GeoHas ...

  5. 基于百度地图的电子围栏的实现之地理位置检索

    在上前面电子围栏实现的基础添加地理位置检索的功能,即用户打开电子围栏设置时,根据想定位的地理位置来进行检索并在地图上进行标注.首先得在页面中动态的添加一个检索框,js实现代码如下: function ...

  6. mongodb 字段检索_如何在MongoDB中创建,检索,更新和删除记录

    mongodb 字段检索 介绍 (Introduction) MongoDB is a free and open-source NoSQL document database used common ...

  7. mongodb地理位置索引实现原理

    地理位置索引支持是MongoDB的一大亮点,这也是全球最流行的LBS服务foursquare 选择MongoDB的原因之一.我们知道,通常的数据库索引结构是B+ Tree,如何将地理位置转化为可建立B ...

  8. 图解GeoHash算法--MongoDB 地理位置索引的实现原理

    转载自:http://blog.nosqlfan.com/html/1811.html 地理位置索引支持是MongoDB的一大亮点,这也是全球最流行的LBS服务foursquare 选择MongoDB ...

  9. 图解 MongoDB 地理位置索引的实现原理

    地理位置索引支持是MongoDB的一大亮点,这也是全球最流行的LBS服务foursquare 选择MongoDB的原因之一.我们知道,通常的数据库索引结构是B+ Tree,如何将地理位置转化为可建立B ...

最新文章

  1. python读出文件中的内容_Python读取文本内容
  2. mysql 存储过程逻辑表达 and_MySQL - 存储过程 (二)- 逻辑判断语句
  3. 准备 overlay 网络实验环境 - 每天5分钟玩转 Docker 容器技术(49)
  4. if you can not get the full version within 1 minute
  5. 无限极分类中递归查找一个树结构
  6. 前后端分离+本地服务实时刷新+缓存管理+接口proxy+静态资源增量更新+各种性能优化+上线运维发布——gulp工作流搭建...
  7. cpta 好像有漏洞
  8. 计算机网络【4】传输层
  9. Linux环境变量总结
  10. scala集合day03
  11. 如何简单利用git_stats脚本统计项目的代码量(以及win平台使用时的错误排除)...
  12. 采用微服务和云计算建立有效的物联网模型
  13. [转]使用C#开发一个简单的P2P应用
  14. drupal.behavior 和 document.ready 没有直接的关系
  15. 8000401a错误解决方式(Excel)
  16. 北邮机器人队2020预备队培训(七) ——仿真文件介绍
  17. Sentinel2 哨兵2数据下载方法(USGS)-史上最全讲解
  18. 语言设置修复计算机 没有光盘,如何在Windows中创建系统修复光盘
  19. C语言:数组排序(插入法排序)
  20. yield 跟 yield * 的区别

热门文章

  1. 《python编程:从入门到实践》文件和异常——百万圆周率,pi_million_digits.txt
  2. 小复习1 Python求解一元二次方程解(自定义函数)
  3. 【定时任务】- 基础篇
  4. 程序设计与算法(二)--算法基础
  5. Linux学习笔记(十八) -- 运行程序,出现Failed to load module canberra-gtk-module错误的解决方案
  6. 3d虚拟VR实训教学软件制作
  7. android蓝牙传文件在哪里找,手机蓝牙传输的文件在哪里_华为手机蓝牙传输记录在哪-系统城...
  8. 百度技术沙龙之2013-23
  9. 爬虫系列 一次采集.NET WebForm网站的坎坷历程
  10. 如何使用netsh advfirewall firewall而不是netsh firewall控制Windows Server 2008的防火墙行为