Spring Boot 使用 MySQL 查询附近数据:经纬度范围搜索
要实现根据 MySQL 返回的经纬度查询附近数据,可以按照以下步骤进行操作:
-
确保你的 MySQL 数据库中的表包含经纬度字段,例如'latitude'和'longitude'字段。
-
在 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方法
}
- 创建一个 Spring Data JPA 的 Repository 接口来进行数据库操作。例如:
@Repository
public interface LocationRepository extends JpaRepository<Location, Long> {
List<Location> findByLatitudeBetweenAndLongitudeBetween(Double minLat, Double maxLat, Double minLng, Double maxLng);
}
- 在你的 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);
}
}
- 最后,在你的 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'接口并提供经纬度和距离参数时,你将获得附近的数据。
原文地址: https://www.cveoy.top/t/topic/lTUV 著作权归作者所有。请勿转载和采集!