MongoDB的地理位置查询

package com.tanhua.model.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "user_location")
@CompoundIndex(name = "location_index", def = "{'location': '2dsphere'}")
public class UserLocation implements java.io.Serializable{ 

    private static final long serialVersionUID = 4508868382007529970L;

    @Id
    private ObjectId id;
    @Indexed
    private Long userId; //用户id
    private GeoJsonPoint location; //x:经度 y:纬度
    private String address; //位置描述
    private Long created; //创建时间
    private Long updated; //更新时间 5.1 -6.1
    private Long lastUpdated; //上次更新时间 5.1
}

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.domain.UserLocation;
import com.tanhua.mongo.api.TanhuaApi;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class UserServiceImpl implements TanhuaApi { 
    @Autowired
    private MongoTemplate mongoTemplate;
    //搜附近
    @Override
    public List<Integer> queryNearUser(Long userId, Double value) { 
        //1、根据用户id,查询用户的位置信息
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        if (location==null){ 
            return null;
        }
        //2、已当前用户位置绘制原点
        GeoJsonPoint point=location.getLocation();
        //3、绘制半径
        Distance distance=new Distance(value/1000, Metrics.KILOMETERS);
        //4、绘制圆形
        Circle circle=new Circle(point,distance);
        //5、查询
        Query locationQuery = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> list = mongoTemplate.find(locationQuery, UserLocation.class);
        return CollUtil.getFieldValues(list,"userId",Integer.class);
    }



}
    原文作者:孤礬
    原文地址: https://blog.csdn.net/weixin_45854212/article/details/124663117
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞