You are on page 1of 23
Chapter 7: Using Google Maps Google Maps is one of the many applications bundled with the Android platform. In addition to simply using the Maps application directly, you can also embed it into your own applications and make it do some very cool things. The Android SDK provides the MapFragment class, which displays a map as a fragment (with data obtained from the Google Maps service). The Maps API are distributed as part of the Google Play services SDK. NOTE —_The older Google Maps Android API version 1.0 is officially deprecated as of December 3 2012. Starting from March 3° 2013 you will no longer be able to apply for a Maps API key for version 1.0 of the Google Maps Android API. Existing apps using version 1.0 of the API will, how- ever, continue to work beyond March 3” 2013. If you are currently developing applications that re- quire the use of Google Maps, you are strongly suggested to use the new version 2.0. ‘This chapter contains various recipes on how to use Google Maps in your Android applications and program- matically perform the following: * Display the Google Maps using the * Change the views of Google Maps ‘* Obtain your current location using Google Maps pFragment Add markers to Google Maps How to draw lines on the map Recipe 7.1: Installing the Google Play Services Li- brary Android Versions NA. Permissions NA. Source Code to Download from Wrox.com NA. Before you use the Google Maps API v2.0, you need to download the Google Play services package using the Android SDK Manager. Solution This recipe shows how to download the Google Play services package into the Android SDK folder. You can skip this step if you have already downloaded this. By default, the Android ADT bundle that is provided by Google does not have this package installed. Hence, you need to download this yourself manually. Installing the Google Play Services Library In Eclipse, select Windows | Android SDK Manager. Check the Google Play services item located under the Extras folder (see Figure 7-1) Tired 04 Too Binsates esalaSbe Motors tose Biome armen Art SO {Soca server roe ‘Seascale tage ‘Scone te Streeter ances Pheri + Bans 32 an) > Slane 30) wood? AND iano 36 9) aesane Pheri ‘horimeata 1 oo Pay AK Cxprion Lary etna rot iin vay her ineaea oor My Ler ary Pherae (Sone st er her cmt a er [one wo rer males (ea tm ect 0) her imeaes stow Abomniw Minted (Joon Seterorsis | Wa eee Senor: Qaim! seo tt ele pases. Figure 7-1 Click the Install 1 packag folder: . button. This will install the Google Play services library onto the following /extras/google/google_play_services/libproject/google-play-services_lib/ Importing the Google Play Services Library project into your work- space ‘Once the Google Play services package is downloaded into your Android SDK folder, you need to import the package into your current workspace in Eclipse. In Eclipse, select File | Import... Select Android | Existing Android Code into Workspace, and browse to location of the Google Play services library. In the Import Projects dialog, check the Copy projects into workspace option and then click Finish (see Fig- ure 7-2). Selec decor to Search fo existing An Root Decor |/Uscrsjweimergie/Destop/Andred 4.2/sék(owasraol (Browse. | Propet © avosieiy-sewes ib Vusew/weimeraee/Deion/Angod A28) Sieg A) ( eseeet al) (Caste ae eeroee ern ot [Gasonere - woreing sets: 5) [_ selec. Figure 7-2 ‘You should now see the google-play-services_lib project imported into your workspace (see Figure 7-3). e200 [Java |e Blur lal) % cl pees) ® BA Google APIs [Android 4.2) > wh Android Dependencies, Bsre “V GB gen [Generated Java Files] ¥ #8 com.google.android.gms > [i Builaconfigjava > G) Riava Goassets >Gbin veelibs Dssonieptap acter google~play-services.jar.prope > Gres [cl AndroidManifest.xmi project.properties README.txt Figure 7-3 Recipe 7.2: Displaying Google Maps Android Versions Level 11 and above Permissions Refer to code snippets for permissions required Source Code to Download from Wrox.com GoogleMaps_v2.0.zip ‘You want to display Google Maps in your Android Application using the MapFragment fragment. Solution In this recipe, you will learn how to display the Google Maps in your application. Before you do that, you need to add the Google Play services project that you imported into your workspace in the previous recipe into your current project. Adding the Google Play services Library Create a new Android Application Project and name it as GoogleMaps. Right-click on the GoogleMaps project and select Properties. Select the Android item on the left and click the Add... button on the right (see Figure 7-4). ‘ype fiter wa P Resource ‘Android Lint Preferences Buiders Java Bld Path Drlava Cove Sinle java Corplier lava Editor Jace Location Projec References Run/Debug Settings Task Tags validation Figure 7-4 Project Bulls Target Android 4.2 SF Coogie Arte Vendor Platform API Le ‘Andro Open Scurce Project 42 17 Googie in. 420 (Restore Default: | (Apply) (cance!) ESO} Select the google-play-services_lib project (see Figure 7-5) and click OK and then OK. Gaiman = See ane sees Z cae ae Javadoc rea pas =e Ries or aa = aa ® Figure 7-5 Using the Web browser on your computer, go to the Google APIs Console located at hetps: //code. googie. con/apis/ console, Click the Create... item to create a new API project (see Figure 7-6). Google apis API Project Rename. Delete. Recent projects My GCM Project Other projects Open... Create... Figure 7-6 Give a name to your project and click the Create project button (see Figure 7-7). Create project Entorthe namo for you project: My Google Maps Project] Grosse protec (Cancel) Figure 7-7 ‘You will now be able to see a list of services available. Locate the Google Maps Android API v2 item and turn on the service (see Figure 7-8). "eagle Cou Storage JSON APL Courtesy im: 100,000 equestsiday © cose Compute Encina ‘Reauest acess. Reauest acess. Prog 8 cong isos Andis API 2 a az coogi Maps API v2 Courtesy mt: 25,000, requestaldy Pricing Figure 7-8 Applying for the Google Maps API Key To apply for a k , follow the series of steps outlined next. NOTE Google provides detailed documentation on applying for a Maps API key at he Jdevelopers First, if you are testing the application on an Android device directly connected to your development machine, locate the SDK debug certificate located in the default folder (/Users//. android for OS X users and C: \Users\\ . android for Windows 7 or Windows 8 users). You can verify the ex- istence of the debug certificate by going to Eclipse and selecting Eclipse [Preferences (for OS X) or Window | Preferences (for Windows). Expand the Android item and select Build (see Figure 7-9). On the right side of the window, you can see the debug certificate’s location. NOTE At the time of writing, you need a real device to test Google Maps v2.0. The Android Emulator does not have the Google Play store installed; hence you would not be able to use it to test your Google Maps. e010 Prfereces a ra =e lie en tented pr Fen a tree to etal ta a ae ce (fs aig an ding xr mth St pana hut oe) pumemremin | ad ae Soest eae con tig ee (one [ Ress teas | [Aon Figure 7-9 NOTE For Windows XP users, the default Android folder is C:\Documents and Set~ tings\\Loca ettings\Application Data\Android. The filename of the debug keystore is debug. keystore. This is the certificate that Eclipse uses to sign your application so that it may be run on the Android emulator or devices. Using the debug keystore, you need to ex- tract its SHAL fingerprint using the Xeytoo! application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. You can usually find the keytool application in the C:\Program Piles\Java\\bin folder (for Windows users). Issue the following command (see also Figure 7-10; for Windows users, you can open the Command window and change the directory to where the keytoo! application is located and then type in the command as shown in the figure) to extract the SHAI fingerprint: keytool -list -alias androiddebugkey -keystore “path_to_debug. keystore” -storepass android -keypass android -v e090 (Biandroid = bash = 80x24 Z Wei-Heng-Lees-NacBook-Prot.androia wesnenglees Keytaol —list alias anaroigeabua | ‘las mane: ancrosaazouakey Certitiente Fingerps wes-Meng-Leee-NacBook-Pro: android weinenglees I Figure 7-10 In the preceding command, the following arguments were used: * -List—Shows details about the specified keystore © -alias—Alias for the keystore, which is “androiddebugkey” for debug. keystore * ~keystore—Specifies the location of the keystore * ~storepass—Specifies the password for the keystore, which is “android” for debug. keystore * ~keypass—Specifies the password for the key in the keystore, which is “android” for de- bug. keystore + -v—Specifies verbose mode, which displays all the different certificate fingerprints; in this case, MDS and SHAL NOTE Although you can use the SHA1 fingerprint of the debug keystore to obtain the Maps API key for debugging your application on Android devices, the key will not be valid if you try to export your Android application as an APK file. When you are ready to deploy your application to the An- droid Market (or other methods of distribution), you need to reapply for a Maps AP! key using the certificate that will be used to sign your application. Back in the Google APIs Console page, click on the API Access item on the left and click the Create new Android key... button (see Figure 7-11). Google avis sysop ‘mre sn sage le en Pet ing i Oh ene Py ao oe ced Tu ney oat en arty ae if ‘Authorized API Access ‘Oth 20 aloe uso a shar pce ta with you for ear 6 ‘Sete at) nag tat nen, peers er ‘romaton pata ng je may cota p20 rt pepe rats ‘Simple APL Access ‘Use Pines to ely ya et en you drt aed aca ur dla Ln ey torbeomae app it tres) ere ay. miner Est sous row tw: Doyle sones Date Aetwaee oy womergeeeeardoeroce nt - you rate ne Server ey) Create ne Browse ay Cet new Ande Wf (dete Bae Pa Figure 7-11 Enter the SHA1 key obtained previously followed by a ";" and then the package name of your project. Click Create (see figure 7-12). Configure Android Key for My Google Maps Project ‘This key can be deployed in your Android applications. 'AP| requests are sent directly to Googie from your clans" Android devices. Google verifies that ‘each request originates fom an Android application that matches one of the ceficate SHA fingerprints and package names ised below. You can discover the SHA fingrpin of your ‘developer cortfiate using the following command: keytool -List -v -keyetore mystore.xeystore Leam more OrnehadRaRnaas (One SHA? ceriicatefingersint and package nama (separstad by a samiclon) par lina. Example: 45:85:84 6F:36:AD/ 04:98: 94:84 02; 66:28: 12117:F2:86:26:A0:E0;com.exanple Greate Cancel] Figure 7-12 NOTE In this example, the package name that | have used is net. learn2deve lop. goog lemaps. If you have a different package name for your project, use your own package name. ‘You will now obtain the Google Maps API key (see Figure 7-13). ‘Simple API Access Use API Keys to identy your project when you do nt need to access user data, Loan more Key for Android apps vt corctes) nee APihay, REARS BERSA TES dsr at alowed And Actatd on: Dac 19, 2012612 PM ‘Activated by: woimengleo@ieam2develop.net- you Figure 7-13 Copy and Maps API key and save it somewhere. You will need this key later on, With the first step of the solution complete, it’s time to move to the second step: Displaying the map, Displaying the Map With the Google Maps API key obtained, you are now ready to display Google Maps in your Android applica- tion. In order to display Google Maps in your application using the MapFragment, you need to add a few per- missions in your AndyoidManifest.xml file, You also need to specify your Maps API key here: Suses-permission android:nane="con.google.android providers.gef.permission-READ_GSERVICES" /> earn2develop.googlemaps MainActivity" ng/at d:name-"andreid. intent action MAIN" /> emeta-data android:name="con.googlle android ma

You might also like