본문 바로가기

안드로이드

안드로이드에서 주소를 좌표로 변환 하기(GeoCoder)

안드로이드에서 지도 등을 활용할 때 주소 정보를 좌표 정보로 변환해야 하는 경우가 있다. 이럴 때 사용하는 것이 Android에서 제공되는 클래스인 Geocoder이다. android.location 패키지에 있으며, 주소에서 좌표 혹은 좌표에서 주소 정보를 가져올 수 있다. 사용방법은 간단하다. Geocoder 객체 생성 후 원하는 메서드를 호출해주면 된다. 주로 사용되는 메서드는 아래와 같다.

 

getFromLocation(latitude: Double, longitude: Double, maxResults: Int): List<Address>

위경도 값을 토대로 주소정보를 제공한다.

getFromLocationName(address: String, maxResults: Int): List<Address>

주소명을 토대로 데이터를 제공한다.

 

해당 Address 클래스에서 좌표값 혹은 주소명을 가져올 수 있다.

getAddressLine(index: Int): String

주소명의 경우, 도로명 혹은 지번 주소 등으로 오기 때문에 index로 해당 데이터를 가져와야 한다.

getLatitude()

해당 주소의 위도

getLongitude()

해당 주소의 경도

 

사용 예)

fun getAddressFromLocation(context: Context, location: Location?) {
	location?.run {
		Geocoder(context).getFromLocation(latitude, longitude, 5)?.let { addressList ->
        	doSomething(addressList)
        }
    }
}

fun getAddressFromLocationName(context: Context, name:String) {
	Geocoder(context).getFromLocationName(name, 5)?.let { addressList ->
    	doSomething(addressList)
    }
}

fun doSomething(addressList: List<Address>) {
	if (addressList.isNotEmpty())
            	addressList[0].let { address ->
                	//주소명
                	address.addressLine[0]
                    //위도
                    address.latitude
                    //경도
                    address.longitude
                    /** 
                    * ...
                    * do something
                    * ...
                    */
                }
}

 

참고링크 : 

https://developer.android.com/reference/android/location/Geocoder

 

Geocoder  |  Android 개발자  |  Android Developers

Geocoder public final class Geocoder extends Object java.lang.Object    ↳ android.location.Geocoder A class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (l

developer.android.com

https://developer.android.com/reference/android/location/Address

 

Address  |  Android 개발자  |  Android Developers

Address public class Address extends Object implements Parcelable java.lang.Object    ↳ android.location.Address A class representing an Address, i.e, a set of Strings describing a location. The address format is a simplified version of xAL (eXtensible Add

developer.android.com