2014년 9월 10일 수요일

Add Maps to application (Google Maps)

The key class when working with a map object is the GoogleMap class, models the map object within application. Within UI, a map will be represented by either a MapFragment or MapView object.

Google Map handles the following operations automatically

  • connecting to the Google Maps service
  • downloading map tiles
  • displaying tiles on the device screen
  • displaying various controls such as pan & zoom
  • responding to pan & zoom gestures by moving the map and zooming in/out


Google Maps provides four types of maps: Normal, Hybrid, Satellite, Terrain.
To set the type of a map, use setMapType() of GoogleMap object.
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

Basic steps for adding a map to an Android application
1. Add a fragment
Add a <fragment> element to the Activity's layout file to define a Fragment object, and set android:name attribute to "com.google.android.gms.maps.MapFragment. This will attach a MapFragment to the Activity automatically.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/map"
  android:name="com.google.android.gms.maps.MapFragment"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />
We can also add a MapFragment to an Activity in code like the following:
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.my_container, mMapFragment);
fragmentTransaction.commit();

2. Add map code
After setting the layout file as the content view for the Activity, get a handle to the map by calling findFragmentById() to set some initial options for the map.

mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

3. Verify map availability
Before interacting with a GoogleMap object, we need to make sure that an object can be instantiated.
Check the following example code snippets, this methods can be called from both onCreate() and onResume() to ensure that the map is always available.

private void setupMapIfNeeded() {
  // null check to confirm that the map has not been instantiated
  if (mGoolgeMap == null) {
    mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    
    if (mGoogleMap != null) {
       // verified, it's ok to manipulate the map
    }
  }
}


댓글 없음:

댓글 쓰기