Android/Tip&Tech
android에서 내현재위치 구하기
행복한 수지아빠
2011. 3. 29. 18:08
출처 : http://gxgsung.blog.me/140120805038
안드로이드 SDK 를 이용하여 GPS 위치정보를 쉽게 구하는 방법입니다.
LocationManager 를 호출하여 GPS와 기지국에서 제공하는 위치정보를 얻어옵니다.
Geocoder 를 활용하여 주소를 가져옵니다.
이 예제는 소스코드가 첨부되어 있습니다.
Java 소스
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// LocationListener의 핸들을 얻음
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// GPS로 부터 위치정보를 업데이트 요청
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
// 기지국으로 부터 위치정보를 업데이트 요청
//locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
// 주소를 확인하기 위한 Geocoder KOREA 와 KOREAN 둘다 가능
geoCoder = new Geocoder(this, Locale.KOREAN);
}
public void onLocationChanged(Location location) {
Log.d("location", "location changed");
myLocation = location;
}
public void GetLocations() {
StringBuffer juso = new StringBuffer();
latPoint = myLocation.getLatitude();
lngPoint = myLocation.getLongitude();
speed = (float)(myLocation.getSpeed() * 3.6);
try {
// 위도,경도를 이용하여 현재 위치의 주소를 가져온다.
List<Address> addresses;
addresses = geoCoder.getFromLocation(latPoint, lngPoint, 1);
for(Address addr: addresses){
int index = addr.getMaxAddressLineIndex();
for(int i=0;i<=index;i++){
juso.append(addr.getAddressLine(i));
juso.append(" ");
}
juso.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
|
main.xml
<TextView
android:id="@+id/lblLatitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Latitude:" />
<TextView
android:id="@+id/tvLatitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/lblLongitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Longitude:" />
<TextView
android:id="@+id/tvLongitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
|
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission>
|
* 위치정보를 사용하기위해서는 위와같이 권한을 주어야 합니다.
에뮬레이터로 테스트 하려면 이클립스의 Open Perspective 에서 DDMS 를 선택하고
좌표를 입력후 Send 버튼을 눌러주면 애뮬레이터로 좌표가 전송됩니다.
실제폰에서도 좌표가 정상 표시됩니다.
첨부해놓은 LocationDemo.apk 파일을 안드로이드 단말에 설치하여 테스트해 보실수 있습니다.
안드로이드 2.1 이상의 OS 에서 동작합니다.