Working with the Google Maps Android API in Android Studio
When Google decided to introduce a map service many years ago, it is hard to say whether or not they ever anticipated having a version available for integration into mobile applications. When the first web based version of what would eventually be called Google Maps was introduced in 2005, the iPhone had yet to ignite the smartphone revolution and the company that was developing the Android operating system would not be acquired by Google for another six months. Whatever aspirations Google had for the future of Google Maps, it is remarkable to consider that all of the power of Google Maps can now be accessed directly via Android applications using the Google Maps Android API.
This chapter is intended to provide an overview of the Google Maps system and Google Maps Android API. The chapter will provide an overview of the different elements that make up the API, detail the steps necessary to configure a development environment to work with Google Maps and then work through some code examples demonstrating some of the basics of Google Maps Android integration.
The Elements of the Google Maps Android API
The Google Maps Android API consists of a core set of classes that combine to provide mapping capabilities in Android applications. The key elements of a map are as follows:
- GoogleMap – The main class of the Google Maps Android API. This class is responsible for downloading and displaying map tiles and for displaying and responding to map controls. The GoogleMap object is not created directly by the application but is instead created when MapView or MapFragment instances are created. A reference to the GoogleMap object can be obtained within application code via a call to the getMap() method of a MapView or MapFragment instance.
- MapView - A subclass of the View class, this class provides the view canvas onto which the map is drawn by the GoogleMap object, allowing a map to be placed in the user interface layout of an activity.
- MapFragment – A subclass of the Fragment class, this class allows a map to be placed within a Fragment in an Android layout.
- Marker – The purpose of the Marker class is to allow locations to be marked on a map. Markers are added to a map by obtaining a reference to the GoogleMap object associated with a map and then making a call to the addMarker() method of that object instance. The position of a marker is defined via Longitude and Latitude. Markers can be configured in a number of ways, including specifying a title, text and an icon. Markers may also be made to be “draggable”, allowing the user to move the marker to different positions on a map.
- Shapes – The drawing of lines and shapes on a map is achieved through the use of the Polyline, Polygon and Circle classes.
- UiSettings – The UiSettings class provides a level of control from within an application of which user interface controls appear on a map. Using this class, for example, the application can control whether or not the zoom, current location and compass controls appear on a map. This class can also be used to configure which touch screen gestures are recognized by the map.
- My Location Layer – When enabled, the My Location Layer displays a button on the map which, when selected by the user, centers the map on the user’s current geographical location. If the user is stationary, this location is represented on the map by a blue marker. If the user is in motion the location is represented by a chevron indicating the user’s direction of travel.
Getting Ready to use the Google Maps Android API
The use of the Google Maps Android API in Android Studio is somewhat unusual in that there is more work involved in setting up the environment than there is in actually writing the Java code. Each step must, however, be performed carefully and with great attention to detail to ensure that maps will function within an application. Even the slightest error or missed step will prevent Maps from appearing within an application.
Installing the Google APIs
The APIs for using Google Maps are not included in the standard Android SDK. Instead, they must be downloaded separately before maps can be integrated into an application. To install the Google APIs, start the Android SDK Manager either by selecting Configure -> SDK Manager from the Android Studio welcome screen, or via the Tools -> Android -> SDK Manager menu of the main window. Once the SDK Manager has loaded, locate the section for the latest SDK from the list of packages (at time of writing this is Android 4.4 API 19). From within this category, make sure that the Status entry for Google APIs is set to Installed as illustrated in Figure 48-1 for both the ARM and x86 system images:
Figure 48-1
If either of the packages are listed as not installed, select the check box next to the package name before clicking on the Install packages… button.
Downloading the Google Play Services SDK
The Google Maps Android API is part of the Google Play services SDK, which will need to be downloaded and installed along with the Google Repository package before Maps can be built into an application project.
To perform these installations, return to the Android SDK Manager, scroll down to the section entitled Extras and unfold it if necessary as outlined in Figure 48-2:
Figure 48-2
If the packages are not listed as installed, enable the checkboxes next to both the Google Play services and Google Repository items in the list before clicking on the Install packages… button to initiate the installation process. Once the download has completed, the SDK will have been installed into the sdk/extras/google/google_play_services subfolder of the Android Studio installation directory (the location of which can be found in the SDK Path field at the top of the Android SDK Manager window).
Adding the Google Play Services Library to the Gradle Build Configuration
The Google Play services library project will need to be added to your module level build configuration file (build.gradle) in order to be included in the compilation of the application. Locate the build.gradle file within the Project tool window as shown in Figure 48-3:
Figure 48-3
Once located (making sure not to accidentally select the top level build.gradle file shown at the bottom of the listing in the above figure), double click on the file to load it into the editor where it should read as follows:
apply plugin: 'android' android { compileSdkVersion 19 buildToolsVersion "19.0.3" defaultConfig { minSdkVersion 9 targetSdkVersion 19 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:19.+' }
The dependencies section of the file lists the libraries that are required by the project to successfully compile and run the application associated with the current project. An extra line now needs to be added to this section to reference the newly installed Google Play Services library.
This can be achieved either by manually editing the build.gradle file, or by using the Android Studio Project Structure dialog. To use the latter approach, select the File -> Project Structure… menu option and, in the resulting dialog, select the name of the module in the left hand panel and the Dependencies tab in the main panel as shown in Figure 48-4:
Figure 48-4
Click on the + button in the right hand margin and select Library Dependency from the popup menu. In the Choose Library Dependency dialog (Figure 48 5), locate and select the Google Play Services entry before clicking on the OK button:
Figure 48-5
After returning to the Project Structure dialog, click on the Apply button followed by OK to commit the change to the project. A review of the build.gradle file should now show that the play services library has been added to the dependencies for the current module:
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:19.+' compile 'com.google.android.gms:play-services:+' }
Clearly, the same result could have been achieved by manually adding the dependency line to the gradle build file, though the Project Structure approach avoids the necessity to identify the correct syntax and naming for library dependencies.
Once the new dependency has been added to the file, synchronize the project with the build file by selecting the Tools -> Android -> Sync Project with Grade Files menu option.
Obtaining Your Developer Signature
Before an application can make use of the Google Maps Android API, it must first be registered within the Google APIs Console. Before an application can be registered, however, the developer signature (also referred to as the SHA-1 fingerprint) associated with your development environment must be identified. This is contained in a keystore file located in the .android subdirectory of your home directory and may be obtained using the keytool utility provided as part of the Java SDK.
Open a terminal window or command prompt and change directory to the .android folder in your home directory before running the following command:
keytool -list -v -keystore debug.keystore
If an error appears indicating that the keytool command cannot be found, make sure that the Java SDK bin directory is included in your PATH environment variable as outlined in the Android Studio installation chapter of this book. If you are unsure of the JDK location, it can be found from within Android Studio by selecting the File -> Project Structure… menu option, selecting SDK Location from the left hand panel and referring to the JDK location setting in the main panel.
Enter the password, if you have one configured, when prompted by keytool, or simply press the keyboard Enter key if no password has been configured. Assuming that the command executed successfully, output similar to the following will appear:
Alias name: androiddebugkey Creation date: Nov 8, 2013 Entry type: PrivateKeyEntry Certificate chain length: 1 Certificate[1]: Owner: CN=Android Debug, O=Android, C=US Issuer: CN=Android Debug, O=Android, C=US Serial number: 64ab39c8 Valid from: Fri Nov 08 09:59:01 EST 2013 until: Sun Nov 01 09:59:01 EST 2043 Certificate fingerprints: MD5: 1A:6F:7B:06:52:A7:41:7B:A3:83:57:E4:B3:19:C5:83 SHA1: 93:2B:B0:D5:32:DD:04:D7:1C:29:F0:D3:D2:18:77:B5:D4:EE:FC:2C SHA256: 46:33:1C:3F:17:DB:AB:13:99:88:AD:54:C1:F5:6F:31:02:CD:38:49:23: 6A:92:D7:E7:50:78:D1:2F:50:14:F3 Signature algorithm name: SHA256withRSA Version: 3
The developer key is the sequence of codes prefixed with SHA1:.
Registering the Project in the Google APIs Console
The next step is to create a project in the Google APIs Console and enable it to make use of the Google Maps Android API service. The Google APIs Console can be accessed using the following URL where you will be required to sign in using your existing Google account information:
https://code.google.com/apis/console/
If this is the first time you have created a project in the console, begin by clicking on the Create Project button to create a new project.
With the newly created project selected, click on the Enable an API button to display an alphabetical list of APIs and services available to the project.
Figure 48-6
Scroll down the list of services until the Google Maps Android API v2 entry comes into view. Change the status of the API from OFF to ON (Figure 48-7) and agree to the terms of service agreement that will subsequently appear.
Figure 48-7
Once the API has been enabled, scroll to the top of the page and select the Credentials option from the left hand navigation panel which will display the page shown in Figure 48-8:
Figure 48-8
Click on the Create new key button and, in the resulting panel, select the Android key button.
In the Create an Android key and configure allowed Android applications dialog, paste the previously obtained SHA-1 fingerprint into the text box, making sure that you place a semi-colon (;) at the end of the key. Immediately after the semi-colon, enter the package name of the application that will require access to the Google Maps Android API. For example:
5B:AC:37:4E:87:66:2A:1A:9D:23:DE:DD:BA:AF:E2:B9:60:D1:C4;com.ebookfrenzy.mapdemo.mapdemo
Once the fingerprint and package name have been entered, click on the Create button to create the key, at which point the Credentials screen will update to include the new “Key for Android applications” including a line listed as API key:
Figure 48-9
Currently, the generated API key in this example is configured only for use with an application with the package name of com.ebookfrenzy.mapdemo.mapdemo. Additional applications may be added to the API key by clicking on the Edit allowed Android application link and entering additional lines consisting of the SHA-1 fingerprint and the application package name.
At this point, the development environment is set up to enable maps to be used within a specific application. The next step is to set up the application project itself to use maps. This begins with making some additions to the application’s Android manifest file.
Adding Map Support to the AndroidManifest.xml File
Before maps can be used in an application, some additional entries need to be added to the application’s Android Manifest file. Within Android Studio, locate the AndroidManifest.xml file for the project for which maps support is required and for which the package name was used when generating the API key. Immediately before the </application> tag, enter the following lines (where <api_key> is replaced by the API Key generated for your development system and application in the API Console):
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="<api_key>"/> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
In addition, a number of permissions need to be added to the manifest file. The following permissions are mandatory, where <package_name> is replaced by the application package name (for example com.ebookfrenzy.mapdemo.mapdemo):
<permission android:name="<package_name>.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name= "<package_name>.permission.MAPS_RECEIVE"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name= "android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name= "com.google.android.providers.gsf.permission.READ_GSERVICES"/>
The following permissions are optional, but are necessary if the application is required to obtain the current location of the device:
<uses-permission android:name= "android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name= "android.permission.ACCESS_FINE_LOCATION"/>
Finally, an entry needs to be added to the manifest file to indicate that the maps features are only available when the application is running on a device that supports OpenGL ES version 2 or later:
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
Bringing these settings together, a typical AndroidManifest.xml file with Google Maps support might, therefore, read as follows:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ebookfrenzy.mapdemo.mapdemo" > <permission android:name= "com.ebookfrenzy.mapdemo.mapdemo.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name= "com.ebookfrenzy.mapdemo.mapdemo.permission.MAPS_RECEIVE"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name= "com.google.android.providers.gsf.permission.READ_GSERVICES"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-feature android:glEsVersion="0x00020000" android:required="false"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name= "com.ebookfrenzy.mapdemo.mapdemo.MapDemoActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="<api_key>"/> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application> </manifest>
Checking for Google Play Services Support
Since the use of the Google Maps Android API requires that the target device support Google Play services, it is important that the application check to make sure those services are available and enabled on a device before attempting to render a map. This can be achieved by making a call to the isGooglePlayServicesAvailable() method contained within the GooglePlayServicesUtil package.
When called, this method will return a status value indicating whether the service is available, missing, invalid, disabled or requires an update. Some of the error states are categorized as being user recoverable. Whether or not the error is recoverable or not can be identified by a call to the GooglePlayServicesUtil isUserRecoverableError() method, passing through the status value as an argument.
In the event that the failure is user recoverable, a call to the getErrorDialog() method will display a dialog to the user providing the option either to enable Google Play on the device or, if necessary, download and install the Google Play services package from the Google Play Store.
Understanding Geocoding and Reverse Geocoding
It is impossible to talk about maps and geographical locations without first covering the subject of Geocoding. Geocoding can best be described as the process of converting a textual based geographical location (such as a street address) into geographical coordinates expressed in terms of longitude and latitude. Geocoding can be achieved using the Android Geocoder class. An instance of the Geocoder class can, for example, be passed a string representing a location such as a city name, street address or airport code. The Geocoder will attempt to find a match for the location and return a list of Address objects that potentially match the location string, ranked in order with the closest match at position 0 in the list. A variety of information can then be extracted from the Address objects, including the longitude and latitude of the potential matches.
The following code, for example, requests the location of the National Air and Space Museum in Washington, D.C.:
import java.io.IOException; import java.util.List; import android.location.Address; import android.location.Geocoder; . . . double latitude; double longitude; List<Address> geocodeMatches = null; try { geocodeMatches = new Geocoder(this).getFromLocationName( "600 Independence Ave SW, Washington, DC 20560", 1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!geocodeMatches.isEmpty()) { latitude = geocodeMatches.get(0).getLatitude(); longitude = geocodeMatches.get(0).getLongitude(); }
Note that the value of 1 is passed through as the second argument to the getFromLocationName() method. This simply tells the Geocoder to return only one result in the array. Given the specific nature of the address provided, there should only be one potential match. For more vague location names, however, it may be necessary to request more potential matches and allow the user to choose the correct one.
The above code is an example of forward-geocoding in that coordinates are calculated based on a text location description. Reverse-geocoding, as the name suggests, involves the translation of geographical coordinates into a human readable address string. Consider, for example, the following code:
import java.io.IOException; import java.util.List; import android.location.Address; import android.location.Geocoder; . . . List<Address> geocodeMatches = null; String Address1; String Address2; String State; String Zipcode; String Country; try { geocodeMatches = new Geocoder(this).getFromLocation(38.8874245, -77.0200729, 1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!geocodeMatches.isEmpty()) { Address1 = geocodeMatches.get(0).getAddressLine(0); Address2 = geocodeMatches.get(0).getAddressLine(1); State = geocodeMatches.get(0).getAdminArea(); Zipcode = geocodeMatches.get(0).getPostalCode(); Country = geocodeMatches.get(0).getCountryName(); }
In this case the Geocoder object is initialized with latitude and longitude values via the getFromLocation() method. Once again, only a single matching result is requested. The text based address information is then extracted from the resulting Address object.
It should be noted that the geocoding is not actually performed on the Android device, but rather on a server to which the device connects when a translation is required and the results subsequently returned when the translation is complete. As such, geocoding can only take place when the device has an active internet connection.
Adding a Map to an Application
The simplest way to add a map to an application is to specify it in the user interface layout XML file for an activity. The following example layout file shows a MapFragment instance added as the child of a RelativeLayout view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.ebookfrenzy.mapdemo.mapdemo.MapDemoActivity"> <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:name="com.google.android.gms.maps.MapFragment"/> </RelativeLayout>
Assuming that the onCreate() method for the activity contains the standard code to load the layout resource file, the application should run and display a map:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps_demo); }
In the event that a map is not displayed, check the following areas:
- If the application is running on an emulator, make sure that the emulator is running a version of Android that includes the Google APIs.
- Check the LogCat output for any areas relating to authentication problems with regard to the Google Maps API. This usually means the API key was entered incorrectly or that the application package name does not match that specified when the API key was generated.
- Verify that the correct entries and permissions have been added to the Manifest file, including all references to the package name and API key.
- Verify within the Google API Console that the Google Maps Android API has been enabled in the Services panel.
Displaying the User’s Current Location
The user’s current location may be displayed on the map by obtaining a reference to the GoogleMap object associated with the displayed map and calling the setMyLocationEnabled() method of that instance, passing through a value of true. The following code, for example, obtains a reference to the GoogleMap object from the previous example, verifies that the map instance exists and then enables the My Location Layer:
import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; . . . GoogleMap map; map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); if (map != null) map.setMyLocationEnabled(true);
Changing the Map Type
The type of map displayed can be modified dynamically by making a call to the setMapType() method of the corresponding GoogleMap object, passing through one of the following values:
- GoogleMap.MAP_TYPE_NONE – An empty grid with no mapping tiles displayed.
- GoogleMap.MAP_TYPE_NORMAL – The standard view consisting of the classic road map.
- GoogleMap.MAP_TYPE_SATELLITE – Displays the satellite imagery of the map region.
- GoogleMap.MAP_TYPE_HYBRID – Displays satellite imagery with the road maps superimposed.
- GoogleMap.MAP_TYPE_TERRAIN – Displays topographical information such as contour lines and colors.
The following code, for example, switches a map to Terrain mode:
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
Alternatively, the map type may be specified in the XML layout file in which the map is embedded using the map:mapType property together with a value of none, normal, hybrid, satellite or terrain. In order to be able to use this directive, however, it is first necessary to add the map namespace to the XML resource file in which the directives are being used:
xmlns:map="http://schemas.android.com/apk/res-auto"
For example:
<?xml version="1.0" encoding="utf-8"?> <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" map:mapType="hybrid" android:name="com.google.android.gms.maps.MapFragment"/>
Displaying Map Controls to the User
The Google Maps Android API provides a number of controls that may be optionally displayed to the user consisting of zoom in and out buttons, a “my location” button and a compass.
Whether or not the zoom and compass controls are displayed may be controlled either programmatically or within the map element in XML layout resources. In order to configure the controls programmatically, a reference to the UiSettings object associated with the GoogleMap object must be obtained:
UiSettings mapSettings; mapSettings = map.getUiSettings();
The zoom controls are enabled and disabled via calls to the setZoomControlsEnabled() method of the UiSettings object. For example:
mapSettings.setZoomControlsEnabled(true);
Alternatively, the map:uiZoomControls property may be set within the map element of the XML resource file:
map:uiZoomControls="false"
The compass may be displayed either via a call to the setCompassEnabled() method of the UiSettings instance, or through XML resources using the map:uiCompass property. The “My Location” button will only appear when My Location mode is enabled as outlined earlier in this chapter. The button may be prevented from appearing even when in this mode via a call to the setMyLocationButtonEnabled() method of the UiSettings instance.
Handling Map Gesture Interaction
The Google Maps Android API is capable of responding to a number of different user interactions. These interactions can be used to change the area of the map displayed, the zoom level and even the angle of view (such that a 3D representation of the map area is displayed for certain cities).
Map Zooming Gestures
Support for gestures relating to zooming in and out of a map may be enabled or disabled using the setZoomControlsEnabled() method of the UiSettings object associated with the GoogleMap instance. For example, the following code enables zoom gestures for our example map:
UiSettings mapSettings; mapSettings = map.getUiSettings(); mapSettings.setZoomGesturesEnabled(true);
The same result can be achieved within an XML resource file by setting the map:uiZoomGestures property to true or false.
When enabled, zooming will occur when the user makes pinching gestures on the screen. Similarly, a double tap will zoom in whilst a two finger tap will zoom out. One finger zooming gestures, on the other hand, are performed by tapping twice but not releasing the second tap and then sliding the finger up and down on the screen to zoom in and out respectively.
Map Scrolling/Panning Gestures
A scrolling, or panning gesture allows the user to move around the map by dragging the map around the screen with a single finger motion. Scrolling gestures may be enabled within code via a call to the setScrollGesturesEnabled() method of the UiSettings instance:
UiSettings mapSettings; mapSettings = map.getUiSettings(); mapSettings.setScrollGesturesEnabled(true);
Alternatively, scrolling on a map instance may be enabled in an XML resource layout file using the map:uiScrollGestures property.
Map Tilt Gestures
Tilt gestures allow the user to tilt the angle of projection of the map by placing two fingers on the screen and moving them up and down to adjust the tilt angle. Tilt gestures may be enabled or disabled via a call to the setTiltGesturesEnabled() method of the UiSettings instance, for example:
UiSettings mapSettings; mapSettings = map.getUiSettings(); mapSettings.setTiltGesturesEnabled(true);
Tilt gestures may also be enabled and disabled using the map:uiTiltGestures property in an XML layout resource file.
Map Rotation Gestures
By placing two fingers on the screen and rotating then in a circular motion, the user may rotate the orientation of a map when map rotation gestures are enabled. This gesture support is enabled and disabled in code via a call to the setRotateGesturesEnabled() method of the UiSettings instance, for example:
UiSettings mapSettings; mapSettings = map.getUiSettings(); mapSettings.setRotateGesturesEnabled(true);
Rotation gestures may also be enabled or disabled using the map:uiRotateGestures property in an XML layout resource file.
Creating Map Markers
Markers are used to notify the user of locations on a map and take the form of either a standard or custom icon. Markers may also include a title and optional text (referred to as a snippet) and may be configured such that they can be dragged to different locations on the map by the user. When tapped by the user an info window will appear displaying additional information about the marker location.
Markers are represented by instances of the Marker class and are added to a map via a call to the addMarker() method of the corresponding GoogleMap object. Passed through as an argument to this method is a MarkerOptions class instance containing the various options required for the marker such as the title and snippet text. The location of a marker is defined by specifying latitude and longitude values, also included as part of the MarkerOptions instance. For example, the following code adds a marker including a title, snippet and a position to a specific location on the map:
import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; . . . LatLng MUSEUM = new LatLng(38.8874245, -77.0200729); Marker museum = map.addMarker(new MarkerOptions() .position(MUSEUM) .title("Museum") .snippet("National Air and Space Museum"));
When executed, the above code will mark the location specified which, when tapped, will display an info window containing the title and snippet as shown in Figure 48-10:
Figure 48-10
Controlling the Map Camera
Because Android device screens are flat and the world is a sphere, the Google Maps Android API uses the Mercator projection to represent the earth on a flat surface. The default view of the map is presented to the user as though through a camera suspended above the map and pointing directly down at the map. The Google Maps Android API allows the target, zoom, bearing and tilt of this camera to be changed in real-time from within the application:
- Target – The location of the center of the map within the device display specified in terms of longitude and latitude.
- Zoom – The zoom level of the camera specified in levels. Increasing the zoom level by 1.0 doubles the width of the amount of the map displayed.
- Tilt – The viewing angle of the camera specified as a position on an arc spanning directly over the center of the viewable map area measured in degrees from the top of the arc (this being the nadir of the arc where the camera points directly down to the map).
- Bearing – The orientation of the map in degrees measured in a clockwise direction from North.
Camera changes are made by creating an instance of the CameraUpdate class with the appropriate settings. CameraUpdate instances are created by making method calls to the CameraUpdateFactory class. Once a CameraUpdate instance has been created, it is applied to the map via a call to the moveCamera() method of the GoogleMap instance. To obtain a smooth animated effect as the camera changes, the animateCamera() method may be called instead of moveCamera().
A summary of CameraUpdateFactory methods is as follows:
- CameraUpdateFactory.zoomIn() – Provides a CameraUpdate instance zoomed in by one level.
- CameraUpdateFactory.zoomOut() - Provides a CameraUpdate instance zoomed out by one level.
- CameraUpdateFactory.zoomTo(float) - Generates a CameraUpdate instance that changes the zoom level to the specified value.
- CameraUpdateFactory.zoomBy(float) – Provides a CameraUpdate instance with a zoom level increased or decreased by the specified amount.
- CameraUpdateFactory.zoomBy(float, Point) - Creates a CameraUpdate instance that increases or decreases the zoom level by the specified value.
- CameraUpdateFactory.newLatLng(LatLng) - Creates a CameraUpdate instance that changes the camera's target latitude and longitude.
- CameraUpdateFactory.newLatLngZoom(LatLng, float) - Generates a CameraUpdate instance that changes the camera's latitude, longitude and zoom.
- CameraUpdateFactory.newCameraPosition(CameraPosition) - Returns a CameraUpdate instance that moves the camera to the specified position. A CameraPosition instance can be obtained using CameraPosition.Builder().
The following code, for example, zooms in the camera by one level using animation:
map.animateCamera(CameraUpdateFactory.zoomIn());
The following code, on the other hand, moves the camera to a new location and adjusts the zoom level to 10 without animation:
private static final LatLng MUSEUM = new LatLng(38.8874245, -77.0200729); map.moveCamera(CameraUpdateFactory.newLatLngZoom(MUSEUM, 10));
Finally, the next code example uses CameraPosition.Builder() to create a CameraPosition object with changes to the target, zoom, bearing and tilt. This change is then applied to the camera using animation:
CameraPosition cameraPosition = new CameraPosition.Builder() .target(MUSEUM) .zoom(10) .bearing(70) .tilt(25) .build(); map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Summary
This chapter has provided an overview of the key classes and methods that make up the Google Maps Android API and outlined the steps involved in preparing both the development environment and an application project to make use of the API.