gimmickbutreal

[MySQL] 경위도를 이용하여 두 점 사이의 거리 구하기 본문

Algorithm/SQL

[MySQL] 경위도를 이용하여 두 점 사이의 거리 구하기

isshosng 2022. 9. 9. 16:54

SQL에서 경위도 값을 이용하여 두 점 사이의 거리를 구하는 방법입니다.

 

public static void distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results) {
    throw new RuntimeException("Stub!");
}

안드로이드에선 위 코드처럼 location class에서 해당 메서드 기능을 제공하고 있습니다.

아래 코드처럼 사용하면 됩니다.

LatLng position = markerOptions.get(i).getPosition(); // 처음 위치
LatLng nextPosition = markerOptions.get(i + 1).getPosition(); // 다음 위치
// 두 지점간 거리 계산
Location.distanceBetween(position.latitude, position.longitude,
        nextPosition.latitude, nextPosition.longitude, results);

 

저는 현재 Spring Boot 기반에서 웹 개발을 하고 있기 때문에 SQL Workbench를 사용하고 있습니다.

 

 

1
2
3
4
5
6
7
SELECT * ,
(6371*ACOS(COS(RADIANS('사용자의 위도'))*COS(RADIANS(lat))*COS(RADIANS(lng)-RADIANS('사용자의 경도'))
+SIN(RADIANS('사용자의 위도'))*SIN(RADIANS(lat))))
AS DISTANCE
FROM board
HAVING DISTANCE<= 0.5 // 범위(km)
ORDER BY DISTANCE;
cs

위처럼 나타내면 됩니다.

지구의 평균 반지름이 6371km이기 때문에 처음에 6371을 곱해줍니다. 

GPS 분야에서 많이 쓰이는 WGS84 좌표계 기준으로 작성하였습니다.

 

@Query(value = "select b.id, b.title, b.order_detail, b.minimum_order_amount, b.delivery_charge, " +
        "b.store_type, b.store_name, b.content, b.username, b.created_date, b.lat, b.lng, b.modified_date, " +
        "(6371*ACOS(COS(RADIANS(?3))) * COS(RADIANS(b.lat)) * COS(RADIANS(b.lng)-RADIANS(?4) + SIN(RADIANS(?3)) * SIN(RADIANS(b.lat)))) " +
        "AS distance from Board b order by distance asc limit ?2, ?1", nativeQuery = true)

저의 경우, 자바 코드에선 BoardRepository안에 기록하였습니다.