개발하는 두더지

[Android] Fragment에 구글맵(GoogleMap) 띄우기 본문

Java,Android

[Android] Fragment에 구글맵(GoogleMap) 띄우기

덜지 2017. 5. 18. 14:43


GoogleMap SDK 설치 및 API KEY 발급받기 (  http://duzi077.tistory.com/120 ) 참조


Fragment 구현 ( http://duzi077.tistory.com/119 ) 참조



Fragment에 Google Map을 올려보도록 하겠습니다.






fragment_fragment1.xml

Fragment에서 구글맵을 사용할때는 com.google.android.gms.maps.MapView 를 사용합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">

<!-- Activity에서는 fragment로 구현해야되지만
Fragment로 구현하기위해서는 MapView를 사용해야함-->
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
/>

</RelativeLayout>



Fragment1.java


1. onCreateView() 에서 View와 GoogleMap을 초기화합니다.

findViewById()를 호출하여 지도 객체의 핸들을 가져온다음 getMapAsync()를 사용하여 지도 콜백을 등록합니다.


2. OnMapReadyCallback 인터페이스를 구현하여 onMapReady() 메서드를 재정의합니다.



public class Fragment1 extends Fragment
implements OnMapReadyCallback ,
{
private MapView mapView = null;

public Fragment1()
{
// required
}


@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_fragment1, container, false);

mapView = (MapView)layout.findViewById(R.id.map);
mapView.getMapAsync(this);

return layout;
}

@Override
public void onStart() {
super.onStart();
mapView.onStart();
}

@Override
public void onStop() {
super.onStop();
mapView.onStop();
}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}

@Override
public void onResume() {
super.onResume();
mapView.onResume();
}

@Override
public void onPause() {
super.onPause();
mapView.onPause();
}

@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}

@Override
public void onDestroy() {
super.onDestroy();
mapView.onLowMemory();
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

//액티비티가 처음 생성될 때 실행되는 함수

if(mapView != null)
{
mapView.onCreate(savedInstanceState);
}
}

@Override
public void onMapReady(GoogleMap googleMap) {
LatLng SEOUL = new LatLng(37.56, 126.97);

MarkerOptions markerOptions = new MarkerOptions();

markerOptions.position(SEOUL);

markerOptions.title("서울");

markerOptions.snippet("수도");

googleMap.addMarker(markerOptions);

googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL);

googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
}

}



Comments