액티비티 시작할때 테드퍼미션으로 권한체크 후 현재 위치 가져오는 방법
개념 :
1. TedPermission 으로 권한체크
2. FusedLocationProviderClient 로 내 위치 저장
3. 구글맵에 마커 표시 ( 반경 Circle 도 표시)
1. 초기 설정
1 2 3 4 5 6 7 8 | //gradle : app compile 'gun0912.ted:tedpermission:1.0.2' compile 'com.google.android.gms:play-services-maps:11.0.2' compile 'com.google.android.gms:play-services-location:11.0.2' //Manifest <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> | cs |
https://console.developers.google.com/apis/library 에서 api 키 발급
빠르고 쉬운 방법: Android Studio가 생성한 google_maps_api.xml
파일에 있는 링크를 사용합니다.
google_maps_api.xml
파일에 있는 링크를 복사하여 브라우저에 붙여넣습니다. 링크를 누르면 Google API Console로 이동하고, URL 매개변수를 통해 필수 정보를 Google API Console에 제공하므로, 개발자가 수동으로 입력해야 하는 항목이 줄어듭니다.- 지침에 따라 Google API Console에서 새 프로젝트를 생성하거나 기존 프로젝트를 선택합니다.
- 프로젝트의 Android 제한 API 키를 생성합니다.
- 생성된 API 키를 복사하고 Android Studio로 돌아간 다음,
google_maps_api.xml
파일의 <string> 요소에 API 키를 붙여넣습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //Manifest <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyB3QTRe9zJZwXJ6ly732Xv2l22nQnu5QD0" /> //values -> google_maps_api.xml <resources> <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSyCvB72oHfgzjT7UKiy_ISHw2aPHFQbu2Ns</string> </resources> | cs |
이 부분은 잘 모르겠음
2. Layout 맵 설정
1 2 3 4 5 6 7 8 9 | <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.a0b.move2dinerforuser.ActivityMaps" /> | cs |
3. 권한 받아온 후 내 위치 가져오기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | //클래스 멤버변수 private boolean isGPSEnabled, isNetworkEnabled private MyPermissionListener mPermissionListener; private GoogleMap googleMap; private FusedLocationProviderClient fusedLocationProviderClient; private double myLatitude, myLongitude; @Override protected void onCreate(Bundle savedInstanceState) { mPermissionListener = new MyPermissionListener(); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); new TedPermission(ActivityMaps.this) .setPermissionListener(mPermissionListener) .setDeniedMessage("위치 권한이 필요합니다\n1.설정을 누르세요\n2.권한을 누르세요\n3.위치를 켜주세요") .setPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION) .setGotoSettingButton(true) .setGotoSettingButtonText("설정") .check(); //권한 설정되면 밑의 클래스로 넘어감 } private class MyPermissionListener implements PermissionListener { private LocationManager locationManager = (LocationManager) ActivityMaps.this.getSystemService(Context.LOCATION_SERVICE); @Override public void onPermissionGranted() { isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isNetworkEnabled || !isGPSEnabled) { }else{ getCurrentLocation();// 권한을 받은 상태 } } @Override public void onPermissionDenied(ArrayList<String> deniedPermissions) { Toast.makeText(ActivityMaps.this, "권한 필요 : " + deniedPermissions.toString(), Toast.LENGTH_SHORT).show(); } } private void getCurrentLocation() { OnCompleteListener<Location> completeListener = new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { if (task.isSuccessful() && task.getResult() != null) { currentLocation = task.getResult(); myLatitude = currentLocation.getLatitude(); myLongitude = currentLocation.getLongitude(); myLocationLatLng = new LatLng(myLatitude, myLongitude); mapSync(); } else { } } }; fusedLocationProviderClient.getLastLocation().addOnCompleteListener(ActivityMaps.this, completeListener); } private void mapSync() { SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(map); mapFragment.getMapAsync(ActivityMaps.this); //onMapReady() 실행됨 } | cs |
4. addMarker
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @Override public void onMapReady(GoogleMap googleMap) { this.googleMap = googleMap; this.googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); this.googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.521504, 126.954152), 10)); //처음에 서울에서부터 시작 LatLng myLocationLatLng = new LatLng(myLatitude, myLongitude); MarkerOptions myMarker = new MarkerOptions().position(myLocationLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_on)).title("MyLocation"); CircleOptions circle = new CircleOptions().center(myLocationLatLng).radius(rad).strokeWidth(0f).fillColor(Color.parseColor("#33ff0000")); googleMap.addCircle(circle); googleMap.addMarker(myMarker); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocationLatLng, 16)); } | cs |
내 위치 마커 이미지는 스스로 구하기
'Android' 카테고리의 다른 글
CustomTitlebar 재활용 (0) | 2017.11.20 |
---|---|
슬라이더 무한 + 자동 스크롤 + Indicator 연동 (ViewPager) (0) | 2017.11.20 |
리사이클러뷰 리스트 비었을때 EmptyView 보여주기 (0) | 2017.11.11 |
움직이는 로딩 이미지 AppCompatDiaLog + Lotti (1) | 2017.11.09 |
횡스크롤 안되는 FragmentViewPager + 하단 네비게이션 (1) | 2017.11.09 |