Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

76. 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...

76.1 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:

GoogleMapThe 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, MapFragment or SupportMapFragment 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.

SupportMapFragment – A subclass of the Fragment...

76.2 Creating the Google Maps Project

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Google Maps Activity template before clicking on the Next button.

Enter MapDemo into the Name field and specify com.ebookfrenzy.mapdemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

76.3 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. In order to make the process easier, however, Android Studio adds some additional files to the project when the Google Maps Activity option is selected during the project creation process. One of these files is named google_maps_api.xml and is located in the app -> res -> values folder of the project.

Contained within the google_maps_api.xml file is a link to the Google Developer console. Copy and paste this link into a browser window. Once loaded, a page...

76.4 Adding the Apache HTTP Legacy Library Requirement

Since this example project will be built for use with Android version 9.0 or later, the following declaration needs to be added within the <application> section of the AndroidManifest.xml file as follows:

.

.

   <application

            android:allowBackup="true"

            android:icon="@mipmap/ic_launcher"

            android:label="@string/app_name"

            android:roundIcon="@mipmap/ic_launcher_round"

            android:supportsRtl="true"

            android:theme=...

76.5 Testing the Application

Perform a test run of the application to verify that the API key is correctly configured. Assuming that the configuration is correct, the application will run and display a map on the screen.

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. The current operating system can be changed for an AVD configuration by selecting the Tools -> Android -> AVD Manager menu option, clicking on the pencil icon in the Actions column of the AVD followed by the Change… button next to the current Android version. Within the system image dialog, select a target which 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...

76.6 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...

76.7 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 the SupportMapFragment instance added to the activity_maps.xml file created by Android Studio:

<fragment 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"

    android:id="@+id/map"

    tools:context=".MapsActivity"

    android:name="com.google.android.gms.maps.SupportMapFragment"/>

76.8 Requesting Current Location Permission

As outlined in the chapter entitled “Making Runtime Permission Requests in Android”, certain permissions are categorized as being dangerous and require special handling for Android 6.0 or later. One such permission gives applications the ability to identify the user’s current location. By default, Android Studio has placed a location permission request within the AndroidManifest.xml file. Locate this file located under app -> manifests in the Project tool window and locate the following permission line:

<uses-permission

          android:name="android.permission.ACCESS_FINE_LOCATION" />

This will ensure that the app is given the opportunity to provide permission for the app to obtain location information at the point that the app is installed on older versions of Android, but to fully support Android 6.0 or later, the app must also specifically...

76.9 Displaying the User’s Current Location

Once the appropriate permission has been granted, 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.

When the map is ready to display, the onMapReady() method of the activity is called. This method will also be called when the map is refreshed within the onRequestPermissionsResult() method above. By default, Android Studio has implemented this method and added some code to orient the map over Australia with a marker positioned over the city of Sidney. Locate and edit the onMapReady() method in the MapsActivity.java file to remove this template code and to add code to check the location permission has been granted before enabling display of the user’s current location. If permission has not been granted, a request is made to the user...

76.10 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 map superimposed.

·GoogleMap.MAP_TYPE_TERRAIN – Displays topographical information such as contour lines and colors.

The following code change to the onMapReady() method, for example, switches a map to Satellite mode:

.

.

if (mMap != null) {

    int permission = ContextCompat.checkSelfPermission(

           ...

76.11 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:

import com.google.android.gms.maps.UiSettings;

.

.

UiSettings mapSettings;

mapSettings = mMap.getUiSettings();

The zoom controls are enabled and disabled via the 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"

...

76.12 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).

76.12.1 Map Zooming Gestures

Support for gestures relating to zooming in and out of a map may be enabled or disabled using the setZoomGesturesEnabled() method of the UiSettings object associated with the GoogleMap instance. For example, the following code disables zoom gestures for our example map:

UiSettings mapSettings;

mapSettings = map.getUiSettings();

mapSettings.setZoomGesturesEnabled(false);

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...

76.13 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...

76.14 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...

76.15 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.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth