본문 바로가기
MOBILE/Android

안드로이드 현재 내 위치값(좌표값) 구하기

by 지구 2018. 8. 5.

출처 : http://whiteduck.tistory.com/124



이렇게 로그인하면 현재 내 위치받아와서 날씨랑 미세먼지를 가져오게끔 위젯을 만들어야했다.

날씨랑 미세먼지를 가져오려면 최우선으로 현재 내 위치값을 가져와야했으니, 그 방법에 대해 이제 정리하려고 한다!


* 사용방법 *

1. 위치를 사용하기 위해 AndroidManifest.xml 에 Permission 을 추가한다.

1
2
3
<!-- 위치값 받아오는데 필요함 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
cs

2. 사용하고자 하는 Activity 또는 Fragment 에서 상단에 필드를 먼저 선언한다.

1
2
private LocationManager locationManager;
private static final int REQUEST_CODE_LOCATION = 2;
cs

3. 사용하고자 하는 Activity (라면 onCreate 메소드에) 또는 Fragment 에서 (라면 onActivityCreated 메소드에) 아래 구문을 추가한다.

위치정보를 받아오기 위해 locationManager 를 선언,

+Activity라면 getContext() 부분 삭제해주셔야 합니다.

1
2
3
4
5
6
7
8
9
10
11
//사용자의 위치 수신을 위한 세팅
locationManager = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);
//사용자의 현재 위치
Location userLocation = getMyLocation();
if( userLocation != null ) {
    double latitude = userLocation.getLatitude();
    double longitude = userLocation.getLongitude();
    userVO.setLat(latitude);
    userVO.setLon(longitude);
    System.out.println("////////////현재 내 위치값 : "+latitude+","+longitude);
}
cs

4. 하단에 getMyLocation 메소드까지 기재해주면 끝!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 사용자의 위치를 수신
*/
private Location getMyLocation() {
    Location currentLocation = null;
    // Register the listener with the Location Manager to receive location updates
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        System.out.println("////////////사용자에게 권한을 요청해야함");
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, this.REQUEST_CODE_LOCATION);
        getMyLocation(); //이건 써도되고 안써도 되지만, 전 권한 승인하면 즉시 위치값 받아오려고 썼습니다!
    }
    else {
        System.out.println("////////////권한요청 안해도됨");
 
        // 수동으로 위치 구하기
        String locationProvider = LocationManager.GPS_PROVIDER;
        currentLocation = locationManager.getLastKnownLocation(locationProvider);
        if (currentLocation != null) {
            double lng = currentLocation.getLongitude();
            double lat = currentLocation.getLatitude();
        }
    }
    return currentLocation;
}
cs


반응형

댓글