| | |
| | | |
| | | import com.xiaopeng.api.vo.automaticPilot.VehiclePosition; |
| | | import org.springframework.data.domain.Sort; |
| | | import org.springframework.data.geo.GeoResults; |
| | | import org.springframework.data.geo.Point; |
| | | import org.springframework.data.geo.Distance; |
| | | import org.springframework.data.geo.Metrics; |
| | | import org.springframework.data.geo.*; |
| | | 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.NearQuery; |
| | | import org.springframework.data.mongodb.core.query.Query; |
| | |
| | | double latitude, |
| | | double distanceInMeters,int num) { |
| | | try { |
| | | // 1. 创建查询点 |
| | | Point referencePoint = new Point(longitude, latitude); |
| | | // // 1. 创建查询点 |
| | | // Point referencePoint = new Point(longitude, latitude); |
| | | // |
| | | // // 2. 构建 NearQuery - 完全使用 NearQuery 的 API |
| | | // NearQuery nearQuery = NearQuery.near(referencePoint, Metrics.KILOMETERS) |
| | | // .maxDistance(distanceInMeters / 1000) // 转成公里 |
| | | // .spherical(true); |
| | | // |
| | | // |
| | | // // 4. 执行查询 - 明确指定集合名 |
| | | // GeoResults<VehiclePosition> geoResults = mongoTemplate.geoNear( |
| | | // nearQuery, |
| | | // VehiclePosition.class, |
| | | // "vehicle_position" // 明确指定集合名,避免映射错误 |
| | | // ); |
| | | // |
| | | // // 5. 提取结果 |
| | | // return geoResults.getContent().stream() |
| | | // .map(geoResult -> geoResult.getContent()) |
| | | // .collect(Collectors.toList()); |
| | | |
| | | // 2. 构建 NearQuery - 完全使用 NearQuery 的 API |
| | | NearQuery nearQuery = NearQuery.near(referencePoint, Metrics.KILOMETERS) |
| | | .maxDistance(distanceInMeters / 1000) // 转成公里 |
| | | .spherical(true); |
| | | |
| | | |
| | | // 4. 执行查询 - 明确指定集合名 |
| | | GeoResults<VehiclePosition> geoResults = mongoTemplate.geoNear( |
| | | nearQuery, |
| | | VehiclePosition.class, |
| | | "vehicle_position" // 明确指定集合名,避免映射错误 |
| | | ); |
| | | |
| | | // 5. 提取结果 |
| | | return geoResults.getContent().stream() |
| | | .map(geoResult -> geoResult.getContent()) |
| | | .collect(Collectors.toList()); |
| | | |
| | | //找到中心点 |
| | | GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude, latitude); |
| | | //构造半径 |
| | | Distance distanceR = new Distance(distanceInMeters / 1000, Metrics.KILOMETERS); |
| | | //画圆 |
| | | Circle circle = new Circle(geoJsonPoint, distanceR); |
| | | // 构造query对象 |
| | | Query query = Query.query(Criteria.where("point").withinSphere(circle)); |
| | | List<VehiclePosition> vehiclePositions = mongoTemplate.find(query, VehiclePosition.class); |
| | | return vehiclePositions; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return new ArrayList<>(); |