Thursday, 21 November 2013

Setting the default value on Google Maps

For the Google Maps on Android, if no option has been specified, it will starts with maximum zoom out (level 2) and centralize to the middle of Earth (Latitude 0.0, Longitude 0.0).

There is two way to set the default values (zoom, latitude, longitude, tilt, rotation, etc): by xml code or by setting the GoogleMapOptions when it has been instantiated.

1. By XML code:
Here is the example from the official document:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:map="http://schemas.android.com/apk/res-auto"
  android:id="@+id/map"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  class="com.google.android.gms.maps.SupportMapFragment"
  map:cameraBearing="112.5"
  map:cameraTargetLat="-33.796923"
  map:cameraTargetLng="150.922433"
  map:cameraTilt="30"
  map:cameraZoom="13"
  map:mapType="normal"
  map:uiCompass="false"
  map:uiRotateGestures="true"
  map:uiScrollGestures="false"
  map:uiTiltGestures="true"
  map:uiZoomControls="false"
  map:uiZoomGestures="true"/>

There are two important points here:
1.1 Add the Google maps NameSpace:
xmlns:map="http://schemas.android.com/apk/res-auto"

1.2 Clear your project after modification or eclipse will shows an error.

2. By instantiation
If you have created the Google Map by instantiation, you can pass an instance of GoogleMapOptions to set the default values.

The main variable is the camera, which sets the values of the default position, default zoom level, default bearing and default tilt. Here is a simple example:

CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(new LatLng(-33, 150))
    .zoom(13)
    .build();

GoogleMapOptions googleOptions = new GoogleMapOptions()
    .camera(camera);

Be aware the the target must be present.

Once done, depending on the type of Google maps (View or fragment), the option could be:
- Fragment:
MapFragment.newInstance(GoogleMapOptions options);

- View:

No comments:

Post a Comment