Monday, February 3, 2014

Android: How to embed Google Map

Well here I am specifically talking about getting it done with Android Studio and with Maps API v2.

First of all you need the Google Play services downloaded using the SDK Manger.


Then add the Google Play services version to your app's manifest file.
<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
Get your Google Maps API key.

  • Go here: https://code.google.com/apis/console/?noredirect and click 'Cloud Console' link.
  • Register a project there and turn on your Google Maps Android App v2 Service
  • Create a new key under APIs & auth -> Credentials
  • Add the key information to the manifest. See below.
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AasdJHJHKSDHfcFJLbZhndBC_fdsd1KEHk"/>
Add permissions in the manifest to access Internet.
<uses-permission android:name="android.permission.INTERNET"/>
Add a map fragment to your layout. Note that I have used SupportMapFragment. That comes with Android Support Repository.
<fragment 
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          class="com.google.android.gms.maps.SupportMapFragment"/>
Check device compatibility. If Google Play Services are not up-to-date on the phone, this will let the user to update then and there.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
int mapResult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (mapResult != ConnectionResult.SUCCESS) {
    GooglePlayServicesUtil.getErrorDialog(mapResult, this, 0).show();
} else {
    mapFragment.getMap().animateCamera(CameraUpdateFactory.zoomIn());
}
That's about it. Now the map should be visible on your app. If not, patiently go through the above check-list again and see what you have missed :)

No comments:

Post a Comment