要实现根据MySQL返回的经纬度查询附近数据,可以按照以下步骤进行操作:

  1. 确保你的MySQL数据库中的表包含经纬度字段,例如latitudelongitude字段。

  2. 在Spring Boot项目中,创建一个实体类来表示数据库表的数据结构,包括经纬度字段。例如:

@Entity
@Table(name = "your_table_name")
public class Location {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private Double latitude;
    
    private Double longitude;
    
    // 其他字段...
    
    // 省略getter和setter方法
}
  1. 创建一个Spring Data JPA的Repository接口来进行数据库操作。例如:
@Repository
public interface LocationRepository extends JpaRepository<Location, Long> {
    List<Location> findByLatitudeBetweenAndLongitudeBetween(Double minLat, Double maxLat, Double minLng, Double maxLng);
}
  1. 在你的Service或Controller中,注入LocationRepository,并使用findByLatitudeBetweenAndLongitudeBetween方法来查询附近的数据。例如:
@Service
public class LocationService {
    private final LocationRepository locationRepository;
    
    public LocationService(LocationRepository locationRepository) {
        this.locationRepository = locationRepository;
    }
    
    public List<Location> findNearbyLocations(Double latitude, Double longitude, Double distance) {
        // 计算最小经度、最大经度、最小纬度和最大纬度
        Double minLat = latitude - (distance / 111.0);
        Double maxLat = latitude + (distance / 111.0);
        Double minLng = longitude - (distance / (111.0 * Math.cos(Math.toRadians(latitude))));
        Double maxLng = longitude + (distance / (111.0 * Math.cos(Math.toRadians(latitude))));
        
        return locationRepository.findByLatitudeBetweenAndLongitudeBetween(minLat, maxLat, minLng, maxLng);
    }
}
  1. 最后,在你的Controller中,使用LocationService来处理请求并返回查询结果。例如:
@RestController
@RequestMapping("/locations")
public class LocationController {
    private final LocationService locationService;
    
    public LocationController(LocationService locationService) {
        this.locationService = locationService;
    }
    
    @GetMapping("/nearby")
    public List<Location> getNearbyLocations(@RequestParam Double latitude, @RequestParam Double longitude, @RequestParam Double distance) {
        return locationService.findNearbyLocations(latitude, longitude, distance);
    }
}

现在,当你访问/locations/nearby接口并提供经纬度和距离参数时,你将获得附近的数据。

springboot根据mysql返回的经纬度查询附近数据

原文地址: https://www.cveoy.top/t/topic/i7Rg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录