| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package com.ydtech.modules.admin.service;
- import cn.hutool.core.collection.CollectionUtil;
- import com.ydtech.modules.admin.model.SysGeographyPosition;
- import com.ydtech.modules.admin.model.po.SysPcAddress;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.geo.*;
- import org.springframework.data.redis.connection.RedisGeoCommands;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.stereotype.Service;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.stream.Collectors;
- @Service
- public class GeoService {
- @Autowired
- private RedisTemplate<String, String> redisTemplate;
- // 添加位置
- public void addLocation(String geoKey,String userId, double longitude, double latitude) {
- redisTemplate.opsForGeo().add(geoKey, new Point(longitude, latitude), userId);
- }
- // 批量添加位置
- public void addLocations(List<SysPcAddress> list, String geoKey) {
- for (SysPcAddress location : list) {
- addLocation(geoKey,location.getUserId(),Double.parseDouble(location.getLongitude()) , Double.parseDouble(location.getLatitude()));
- }
- }
- public void addLocationGeography(List<SysGeographyPosition> list, String geoKey) {
- for (SysGeographyPosition location : list) {
- addLocation(geoKey,location.getId(),Double.parseDouble(location.getLongitude()) , Double.parseDouble(location.getLatitude()));
- }
- }
- public void move(List<String> list, String geoKey) {
- for (String location : list) {
- redisTemplate.opsForGeo().remove(geoKey,location);
- }
- }
- // 查找某位置附近的ID集合
- public List<String> findNearbyIds(String geoKey, double longitude, double latitude, double radius) {
- Circle within = new Circle(new Point(longitude, latitude), new Distance(radius, Metrics.KILOMETERS));
- RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeCoordinates().includeDistance();
- List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = redisTemplate.opsForGeo().radius(geoKey, within, args).getContent();
- if (content .size()==0) return new ArrayList<String>();
- return content.stream()
- .map(result -> result.getContent().getName())
- .collect(Collectors.toList());
- }
- }
|