public class MapsFragment extends Fragment
implements OnMapReadyCallback ,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private static final LatLng DEFAULT_LOCATION = new LatLng(36.109, 126.975);
private static final String TAG = "googlemap_example";
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2002;
private static final int UPDATE_INTERVAL_MS = 15000;
private static final int FASTEST_UPDATE_INTERVAL_MS = 15000;
private GoogleMap googleMap = null;
private MapView mapView = null;
private GoogleApiClient googleApiClient = null;
private Marker currentMarker = null;
private FusedLocationProviderClient mFusedLocationClient;
public MapsFragment()
{
}
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet) {
if ( currentMarker != null ) currentMarker.remove();
if ( location != null) {
LatLng currentLocation = new LatLng( location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocation);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentMarker = this.googleMap.addMarker(markerOptions);
this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
return;
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(DEFAULT_LOCATION);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
currentMarker = this.googleMap.addMarker(markerOptions);
this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(DEFAULT_LOCATION));
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_map, container, false);
mapView = (MapView)layout.findViewById(R.id.map);
mapView.getMapAsync(this);
return layout;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MapsInitializer.initialize(getActivity().getApplicationContext());
if(mapView != null)
{
mapView.onCreate(savedInstanceState);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
// OnMapReadyCallback implements 해야 mapView.getMapAsync(this); 사용가능. this 가 OnMapReadyCallback
this.googleMap = googleMap;
//런타임 퍼미션 요청 대화상자나 GPS 활성 요청 대화상자 보이기전에 지도의 초기위치를 서울로 이동
setCurrentLocation(null, "위치정보 가져올 수 없음", "위치 퍼미션과 GPS 활성 여부 확인");
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 사용권한체크
int hasFineLocationPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
if (googleApiClient == null) {
buildGoogleApiClient();
}
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
}
} else {
if (googleApiClient == null) {
buildGoogleApiClient();
}
googleMap.setMyLocationEnabled(true);
}
}
int check = 0;
private void buildGoogleApiClient() {
if (googleApiClient != null) googleApiClient.disconnect();
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(), this)
.build();
googleApiClient.connect();
}
}
처음에 프래그먼트를 작동시키면 잘되는데
다른프래그먼트를 띄웠다가 다시 맵을 띄우면 에러가 납니다.
이게 에러 메세지 입니다. 코드는 8000자 이내라 잘라서 올리겠습니다. 마지막 부분이 에러가 나는 부분 입니다.
java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0
at com.google.android.gms.common.internal.Preconditions.checkState(Unknown Source:29)
at com.google.android.gms.common.api.internal.zaj.zaa(Unknown Source:14)
at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source:135)
-> at com.example.ddareureung.MapsFragment.buildGoogleApiClient(MapsFragment.java:275)
-> at com.example.ddareureung.MapsFragment.onMapReady(MapsFragment.java:231)
googleApiClient가 null이 아닐때 build하지 않으면 된다고는 하는데 어떻게 해야 할지 감이 안잡히네여