Lesson 139. Google Maps. Creation and adjustment of the project. Map, camera, events

Lesson 139. Google Maps. Creation and adjustment of the project. Map, camera, events

In this lesson:

– create a map application
– customize the map and process its events
– programmatically change the position of the camera

After the topic of getting coordinates, it will be quite logical to consider the topic of Google maps. The topic is simple and not very big, we will have a couple of lessons to consider.

But before we begin to create and create, we will need to do two things.

1) Enable the Google Map Console in the Google Console and get the API key to work

2) Make the project accessible to Google Play services

API key

Let’s start with the first point. To do this, we need to go to Google APIs Console.

If you don’t have a project, google will suggest creating one.

press Create project

The project was created. select from the left Services and a list of services opens.

In this list we are looking for Google Maps Android API v2

Click on the toggle switch (OFF), accept the agreement and again go to the list of services.

But now the service must be switched on

Everything is O.K. Now we follow the key.

To do this, choose from the top left API Access and such a screen opens.

We press a button on it Create new Android key and we are required to enter the SHA1 value of the key that the application will sign.

And they even give instructions on how to do it with the utility keytool

If it is unclear what this is about, I recommend reading Lesson 123. I described everything there in detail.

But the latest versions of Eclipse allow you to get SHA1 without any commands, just go into the settings and there is all the info

We take the contents of the field SHA1 fingerprint

To it, after a semicolon, add the package of the application (in this lesson it will be ru.startandroid.develop.p1391googlemaps), insert in the box and click Create.

The key we needed was a string API key.

Do not close this page yet, we will need this key soon when creating the program.

Be sure to perform the same manipulations when you sign the application for publication on the market with another key.

Google Play services

Now the second point. We will need Google Play services to work with the map.

Open the SDK Manager and look for Extras> there Google Play services (If you plan on supporting Android 2.2, then Google Play services for Froyo). If not already installed, install.

After downloading, look for a folder on your computer as follows: / Extras / google / google_play_services / libproject / google-play-services_lib /. If you suddenly don’t know where the SDK is, you can check it out in Eclipse Settings, Android, SDK Location:

Source texts from a folder google-play-services_lib will need to be imported into Workspace. To do this, click in the Eclipse menu File > Import, we choose Android > Existing Android Code into Workspace, we find google-play-services_lib folder, check the import projects to be done by Copy projects into workspace and click Finish.

project google-play-services_lib should appear in your Workspace

Preliminary preparation is complete, we can create a project.

Let’s create a project:

Project name: P1391_GoogleMaps
Build Target: Android 2.3.3
Application name: GoogleMaps
Package name: ru.startandroid.develop.p1391googlemaps
Create Activity: MainActivity

Setting up the project

Now a little more fuss with the project.

We go into the project properties and add (button Add) A link to a previously imported one google-play-services_lib project.

The manifest must include the following in the tag application:


The first data is our google console key. Here you need to android: value put your API key value that you received and left open in the browser a little earlier. This key is required for the card to work.

The second data is a version of Google Play services. I think this version info is needed to make the map clearly understand how and what is available to it from these services.

Also, in the manifest in the tag manifest we need to add the following permissions:

This is Internet access, checking the availability of the Internet, saving the cache of maps and access to Google web services.

If you’re thinking of working with placement, don’t forget about:

And there, in the tag manifest the requirement is:

Google Maps uses OpenGL ES version 2. On devices that do not support this, the map simply will not appear. So we put restrictions.

Now that’s it. We continue to work as usual.

IN strings.xml add rows:


screen main.xml:


Button and snippet


package ru.startandroid.develop.p1391googlemaps;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public class MainActivity extends FragmentActivity {

  SupportMapFragment mapFragment;
  GoogleMap map;
  final String TAG = "myLogs";

  protected void onCreate(Bundle savedInstanceState) {

    mapFragment = (SupportMapFragment) getSupportFragmentManager()
    map = mapFragment.getMap();
    if (map == null) {

  private void init() {

  public void onClickTest(View view) {

IN onCreate we find our map snippet and get a GoogleMap object from it using the getMap method. Note that this method can return null.

By the way, you can also hang up onCreate to verify that your device has Google Play services. To do this, call the isGooglePlayServicesAvailable () method and it must return SUCCESS. Help in the help.

method init while empty.

IN onClickTest we set the map type with the setMapType method

There are 5 types in total:

MAP_TYPE_NONE – The map will not be available to the public

MAP_TYPE_NORMAL – Normal mode, in which the map starts by default.

MAP_TYPE_SATELLITE – Satellite images

MAP_TYPE_TERRAIN – terrain map

MAP_TYPE_HYBRID – Satellite + Street and Transportation Info

You can get the current type using the getMapType method.

I will run all the tests on a real device because the emulators do not support Google Play services by default. But if you really need to, you can also run the emulator after some manipulations. This is written, for example, here. You need to download two APKs and install them on the emulator.


We save everything, launch the application and see the map as usual.

I had the map when I first started, though I know, but the zoom buttons were visible. The logs had the following text: Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors). In this case, make sure everything is done correctly with the key. If the problem persists, first uninstall this program from the device, clean up the project in Eclipse (Project> Clean menu) and reinstall the program – it helped me.

press Test

The map now displays satellite images

Let’s see what else you can do with the map.

In normal mode, the map can even show the layout of the floors of the building, as close as possible to the zoom of this building.

Here is an example of the 0-th floor of Barcelona Airport. On the right is a floor switch.

We can programmatically disable this feature by the setIndoorEnabled method.

The setBuildingsEnabled method controls the display of 3D buildings.


The gesture and button control of the card is also customizable. To do this, call the getUiSettings method and we will get the UiSettings interface configuration object.

He has a bunch of methods that include / exclude anything:

setAllGesturesEnabled – all gestures

setCompassEnabled – compass (top left)

setMyLocationButtonEnabled – button where you are (must include definition, method setMyLocationEnabled (true))

setRotateGesturesEnabled – Rotation gestures

setScrollGesturesEnabled – Swipe gestures of the map

setTiltGesturesEnabled – gestures change the viewing angle

setZoomControlsEnabled – Zoom buttons

setZoomGesturesEnabled – Zoom gestures

These methods have analogs that begin with is instead set and allow you to get the current values.

You can hang listeners on the map. rewrite the method init:

  private void init() {
      map.setOnMapClickListener(new OnMapClickListener() {
      public void onMapClick(LatLng latLng) {
        Log.d(TAG, "onMapClick: " + latLng.latitude + "," + latLng.longitude);
      map.setOnMapLongClickListener(new OnMapLongClickListener() {
      public void onMapLongClick(LatLng latLng) {
        Log.d(TAG, "onMapLongClick: " + latLng.latitude + "," + latLng.longitude);
      map.setOnCameraChangeListener(new OnCameraChangeListener() {
      public void onCameraChange(CameraPosition camera) {
        Log.d(TAG, "onCameraChange: " + camera.target.latitude + "," + camera.target.longitude);

setOnMapClickListener hangs the OnMapClickListener listener. Its onMapClick method will work when you click on the map and return a LatLng object with coordinates (latitude, longitude) where it was clicked.

setOnMapLongClickListener hangs the listener OnMapLongClickListener. Its onMapLongClick method will work when you long-click on the map and return a LatLng object with coordinates (latitude, longitude) where it was clicked.

setOnCameraChangeListener hangs the OnCameraChangeListener listener. Its onCameraChange method will work when changing the position of the camera, that is, when viewing the map, and will return a CameraPosition object that contains information about the current status of the camera.

CameraPosition should have the following attributes:

– target, type LatLng with coordinate fields: latitude, longitude. This is the point the camera is looking at.

– bearing, the angle of rotation of the camera north of the clock

– tilt, camera angle

– zoom, the current zoom level

Save everything, launch the application. Try short and long presses, rotate the map, move it, change the angle: the logs will display all the information on these operations.


Now let’s look at the possibilities of programmatically changing the position of the camera.

To do this, we will need to create a CameraUpdate object and pass it to one of the methods:

animateCamera (CameraUpdate update) – smooth camera movement

animateCamera (CameraUpdate update, GoogleMap.CancelableCallback callback) – a smooth move and the ability to specify the CancelableCallback listener to notify that the move is complete (onFinish method) or aborted (onCancel method).

animateCamera (CameraUpdate update, int durationMs, GoogleMap.CancelableCallback callback) – smooth moving, CancelableCallback listener and the ability to specify the travel time in milliseconds

moveCamera (CameraUpdate update) – Instant movement, no animation

It remains to be seen how to obtain the CameraUpdate object, which will contain information about moving the camera. CameraUpdateFactory is used for this purpose.

Let’s go in order of methods in help.

newCameraPosition (CameraPosition cameraPosition) – The created CameraUpdate object will contain data about moving the camera to the specified position from the specified settings.

The CameraPosition object reappears here, all of which we considered earlier when talking about a camera change event, and which contains all the camera position info

We use CameraPosition.Builder to create CameraPosition. rewrite the method onClickTest:

  public void onClickTest(View view) {
    CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(-27, 133))
    CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);

We create CameraPosition, specify coordinates (-27,133), zoom (level 5), rotate the map (45 degrees), tilt (20 degrees). And pass the received object to the newCameraPosition method, getting CameraUpdate, which in turn we pass to the animateCamera method.

We’ll save everything, run it, click it Test and we are seeing a smooth move to Australia. The zoom level, angle, and rotation of the camera change as you move.

newLatLng (LatLng latLng) – Move the camera to the specified point.

Everything is simple here. rewrite the method onClickTest:

  public void onClickTest(View view) {
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(new LatLng(
        -27, 133));

Clicking on Test the camera will move to the specified point.

newLatLngBounds (LatLngBounds bounds, int padding) – the camera will show the specified area with indentation

rewrite the method onClickTest:

  public void onClickTest(View view) {
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(
        new LatLngBounds(new LatLng(-39, 112), new LatLng(-11, 154)),

The LatLngBounds object, which is created from two LatLng points, is used to specify the area. These two points will be the lower left (southwest) and upper right (northeast) points of the created area.

The padding parameter is indented (in pixels) from the edges of the screen. That is, if you specify a non-zero padding, the camera will show the specified area of ​​the map not in full-screen mode, but with this indentation.

Clicking on Test the camera will show Australia with an indentation of 100 pixels from the edges of the screen.

newLatLngBounds (LatLngBounds bounds, int width, int height, int padding) – similar to the previous one, but you can specify the size of the rectangle on the screen that will display the displayed area and the indent will operate inside that area.

newLatLngZoom (LatLng latLng, float zoom) – Move the camera to a specified point with the specified zoom level

scrollBy (float xPixel, float yPixel) – Move the camera to the specified number of pixels

zoomBy (float amount) – Change the current zoom level to the specified number (if positive, approximate, if negative, remove).

zoomBy (float amount, Point focus) – change the current zoom to the specified number of levels, and apply the final level to a specified point on the screen

zoomIn / zoomOut – increase / decrease the zoom level by one

zoomTo (float zoom) – Set the specified zoom level

The GoogleMap object has a setPadding method. It sets offsets from the edges of the screen. This affects the status of the standard map controls, and the camera will now take the center of the map into this new restricted area and position itself there.

In the next lesson:

– we place our objects on the map

Discuss in the forum [109 replies]

Leave a Comment