GeoService.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.ydtech.modules.admin.service;
  2. import cn.hutool.core.collection.CollectionUtil;
  3. import com.ydtech.modules.admin.model.SysGeographyPosition;
  4. import com.ydtech.modules.admin.model.po.SysPcAddress;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.geo.*;
  7. import org.springframework.data.redis.connection.RedisGeoCommands;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.stereotype.Service;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.stream.Collectors;
  13. @Service
  14. public class GeoService {
  15. @Autowired
  16. private RedisTemplate<String, String> redisTemplate;
  17. // 添加位置
  18. public void addLocation(String geoKey,String userId, double longitude, double latitude) {
  19. redisTemplate.opsForGeo().add(geoKey, new Point(longitude, latitude), userId);
  20. }
  21. // 批量添加位置
  22. public void addLocations(List<SysPcAddress> list, String geoKey) {
  23. for (SysPcAddress location : list) {
  24. addLocation(geoKey,location.getUserId(),Double.parseDouble(location.getLongitude()) , Double.parseDouble(location.getLatitude()));
  25. }
  26. }
  27. public void addLocationGeography(List<SysGeographyPosition> list, String geoKey) {
  28. for (SysGeographyPosition location : list) {
  29. addLocation(geoKey,location.getId(),Double.parseDouble(location.getLongitude()) , Double.parseDouble(location.getLatitude()));
  30. }
  31. }
  32. public void move(List<String> list, String geoKey) {
  33. for (String location : list) {
  34. redisTemplate.opsForGeo().remove(geoKey,location);
  35. }
  36. }
  37. // 查找某位置附近的ID集合
  38. public List<String> findNearbyIds(String geoKey, double longitude, double latitude, double radius) {
  39. Circle within = new Circle(new Point(longitude, latitude), new Distance(radius, Metrics.KILOMETERS));
  40. RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeCoordinates().includeDistance();
  41. List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = redisTemplate.opsForGeo().radius(geoKey, within, args).getContent();
  42. if (content .size()==0) return new ArrayList<String>();
  43. return content.stream()
  44. .map(result -> result.getContent().getName())
  45. .collect(Collectors.toList());
  46. }
  47. }