Android, MapView, and your Google apiKey: Part 1

MapList

Thanks to the MapView, it’s drop dead easy to put Google Maps into your application.  There are lots of posts out there how to do it.  Interestingly (to me anyway), when I did a quick search of the Android developers mailing list, I was surprised to see that a lot of people had the same problem:  basically, when you look at your MapView, you end up with a grid of white squares.  It kind of sucks.  There are a lot of blog posts and articles out there on how to fix this problem, but this one is for me, and to help me remember it.

The trick to fixing this is setting your Google Maps API key.  Note the layout below:

   1: <?xml version="1.0" encoding="utf-8"?>



   2: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"



   3:     android:id="@+id/mainlayout"



   4:     android:orientation="vertical"



   5:     android:layout_width="fill_parent"



   6:     android:layout_height="fill_parent" >



   7:



   8:     <com.google.android.maps.MapView



   9:         android:id="@+id/mapview"



  10:         android:layout_width="fill_parent"



  11:         android:layout_height="fill_parent"



  12:         android:clickable="true"



  13:         android:apiKey="Your Maps API Key"



  14:     />



  15:



  16: </RelativeLayout>

hotel-key

In particular, pay attention to line #13.  What you have to do is create a Google Maps API key, and then paste it in there.  That’s simple.  How do you do that?  Well it’s simple too, but not as simple as it could be.  The first thing you need to do is to sign your application.  This isn’t a big deal, you have to sign your application before you can publish it anyway.  Android will NOT install an application otherwise.

So, it seems we have two steps here:

  1. Sign your application
  2. Use your signed application to get a Google Maps apiKey.

Generate a private key.  Keep this safer, as if it were the Holy Grail.  Lose this, and as far as the public is concerned, you’re locked out from your own application – you will not be able to update it.  The image below will show you the steps to go through

    "C:\Program Files (x86)\Java\jdk1.6.0_19\bin\keytool" -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -validity 10000

keytoolsample

Once you have that done, build your application (in release mode).  I leave this as an exercise for the reader.

Now that you have your application built, you need to sign it.  This is where jarsigner comes in:

jarsignerAnd the final step is to zipalign your  APK.  You have to do zipalign last.  Basically, you do zipalign for performance reasons.  If you want to know more, RTFM.

C:\android-sdk-windows\tools\zipalign -v 4 HistoricalBuildings-unalign.apk HistoricalBuildings.apk

zipalign

Now, of course, both Eclipse and IntelliJ will handle these steps for you.  But where is the fun in that?