이 튜토리얼에서는 안드로이드 앱에서 두 지리적 위치(위도·경도) 사이의 거리를 계산하는 방법을 단계별로 알아봅니다. 안드로이드 SDK의 Location 클래스가 제공하는 distanceTo() 메서드를 사용하면 복잡한 수학 공식(Haversine 공식 등)을 직접 구현하지 않고도 두 좌표 간 거리를 손쉽게 구할 수 있습니다.
핵심 개념: Location.distanceTo()
android.location.Location 클래스의 distanceTo(Location dest) 메서드는 현재 위치 객체와 대상 위치 객체 사이의 거리를 미터(m) 단위로 반환합니다. 내부적으로 WGS84 타원체 기반의 정밀한 거리 계산을 수행하므로, 실제 지리적 거리와 비교적 가까운 결과를 얻을 수 있습니다.
참고로 distanceTo()의 반환값은 미터 단위이므로, 킬로미터(km)로 표시하고 싶다면 반환값을 1000으로 나누어 주는 것이 좋습니다.
구현 단계
1단계 — 새 프로젝트 생성
안드로이드 스튜디오를 실행한 뒤 File → New Project로 이동하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 거리 결과를 표시할 TextView 하나를 배치하는 간단한 구조입니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
3단계 — MainActivity 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다. 두 개의 Location 객체를 만들어 각각 위도와 경도를 설정한 후, distanceTo()로 거리를 계산하여 TextView에 출력합니다.
import androidx.appcompat.app.AppCompatActivity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
Location currentLocation = new Location("locationA");
currentLocation.setLatitude(17.372102);
currentLocation.setLongitude(78.484196);
Location destination = new Location("locationB");
destination.setLatitude(17.375775);
destination.setLongitude(78.469218);
double distance = currentLocation.distanceTo(destination);
textView.setText("Distance between two Geographic Locations: " + distance + " KMS");
}
}
코드 설명:
new Location("locationA")— 위치 제공자 이름을 지정하여 Location 객체를 생성합니다.setLatitude(),setLongitude()— 각 위치의 위도와 경도를 설정합니다.currentLocation.distanceTo(destination)— 두 위치 사이의 거리를 미터 단위(double)로 반환합니다.textView.setText()— 계산된 거리를 화면에 표시합니다.
4단계 — 매니페스트 파일 확인
androidManifest.xml 파일이 아래와 같이 되어 있는지 확인합니다. 이 예제는 실제 GPS 센서를 사용하지 않고 좌표를 직접 지정하므로 별도의 위치 권한은 필요하지 않습니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭합니다. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 두 지리적 위치 간 거리가 표시됩니다.

마무리 및 확장 아이디어
이처럼 Location.distanceTo() 메서드만으로도 두 지점 간 거리를 몇 줄의 코드로 간단히 계산할 수 있습니다. 실제 프로젝트에서는 FusedLocationProviderClient로 현재 위치를 가져온 뒤 특정 목적지까지의 거리를 계산하거나, 반경 검색(예: 근처 매장 찾기) 기능에 이 방식을 활용할 수 있습니다. 킬로미터 단위로 깔끔하게 표시하려면 String.format("%.2f km", distance / 1000)처럼 소수점 자릿수를 조절하는 것도 좋은 방법입니다.