Chapter 40

Mapping with MapView and MapActivity

One of Google’s most popular services—after Search, of course—is Google Maps, which enables you to map everything from the location of the nearest pizza parlor to directions from New York City to San Francisco (only 2571 miles, or 4135 kilometers for the metric-inclined), and includes street views and satellite imagery.

Most Android devices, not surprisingly, integrate Google Maps. For those that do, there is a mapping activity available to users straight from the main Android launcher. More relevant to you, as a developer, are MapView and MapActivity, which allow you to integrate maps into your own applications. Not only can you display maps, control the zoom level, and allow people to pan around, but you can tie in Android’s location-based services to show where the device is and where it is going.

Fortunately, integrating basic mapping features into your Android project is fairly easy. And with a bit more effort, you can integrate more sophisticated mapping features.

Terms, Not of Endearment

Integrating Google Maps into third-party applications requires agreeing to a fairly lengthy set of legal terms. These terms include clauses that you may find unpalatable.

If you are considering Google Maps, please review these terms closely to determine if your intended use will run afoul of any clauses. You are strongly recommended to seek professional legal counsel if there are any potential areas of conflict.

Also, keep your eyes peeled for other mapping options, based on other sources of map data, such as OpenStreetMap (www.openstreetmap.org/).

Piling On

As of Android 1.5, Google Maps is not strictly part of the Android SDK. Instead, it is part of the Google APIs Add-On, an extension of the stock SDK. The Android add-on system provides hooks for other subsystems that may be part of some devices but not others.

NOTE: Because Google Maps is not part of the Android open source project, some devices lack Google Maps due to licensing issues. For example, at the time of this writing, the Archos 5 Android tablet does not have Google Maps.

By and large, the fact that Google Maps is in an add-on does not affect your day-to-day development. However, bear in mind the following:

  • You will need to create your project with an appropriate target to ensure the Google Maps APIs will be available.
  • To test your Google Maps integration, you will also need an AVD that uses an appropriate target.

The Key to It All

If you download the source code for this book, compile the Maps/NooYawk project, install it in your emulator, and run it, you will probably see a screen with a grid and a couple of pushpins, but no actual maps. That’s because the API key in the source code is invalid for your development machine. Instead, you will need to generate your own API key(s) for use with your application. This also holds true for any map-enabled projects you create on your own from scratch.

Full instructions for generating API keys, for development and production use, can be found on the Android web site. In the interest of brevity, let’s focus on the narrow case of getting NooYawk running in your emulator. Doing this requires the following steps:

  1. Visit the API key signup page and review the terms of service.
  2. Reread those terms of service and make really sure you want to agree to them.
  3. Find the MD5 digest of the certificate used for signing your debug-mode applications (described in detail following this list).
  4. On the API key signup page, paste in that MD5 signature and submit the form.
  5. On the resulting page, copy the API key and paste it as the value of apiKey in your MapView-using layout.

The trickiest part is finding the MD5 signature of the certificate used for signing your debug-mode applications. Much of the complexity is merely in making sense of the concept.

All Android applications are signed using a digital signature generated from a certificate. You are automatically given a debug certificate when you set up the SDK, and there is a separate process for creating a self-signed certificate for use in your production applications. This signature process involves the use of the Java keytool and jarsigner utilities. For the purposes of getting your API key, you only need to worry about keytool.

To get your MD5 digest of your debug certificate, if you are on Mac OS X or Linux, use the following command:

keytool -list -alias androiddebugkey -keystore ~/.android/debug.keystoreImages
 -storepass android -keypass android

On other development platforms, such as Windows, you will need to replace the value of the -keystore switch with the location for your platform and user account (where <user> is your account name):

  • On Windows XP, use C:Documents and Settings<user>.androiddebug.keystore.
  • On Windows Vista or Windows 7, use C:Users<user>.androiddebug.keystore.

The second line of the output contains your MD5 digest, as a series of pairs of hex digits separated by colons.

The Bare Bones

To put a map into your application, you need to create your own subclass of MapActivity. Like ListActivity, which wraps up some of the smarts behind having an activity dominated by a ListView, MapActivity handles some of the nuances of setting up an activity dominated by a MapView. A MapView can be used only by a MapActivity, not by any other type of Activity.

In your layout for the MapActivity subclass, you need to add an element named com.google.android.maps.MapView. This is the “longhand” way to spell out the names of widget classes, by including the full package name along with the class name. This is necessary because MapView is not in the android.widget namespace. You can give the MapView widget whatever android:id attribute value you want, plus handle all the layout details to have it render properly alongside your other widgets.

However, you do need to have the following items:

  • android:apiKey, your Google Maps API key
  • android:clickable = "true", if you want users to be able to click and pan through your map

For example, from the Maps/NooYawk sample application, here is the main layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <com.google.android.maps.MapView android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="00yHj0k7_7vxbuQ9zwyXI4bNMJrAjYrJ9KKHgbQ"
    android:clickable="true" />
</RelativeLayout>

In addition, you will need a couple of extra things in your AndroidManifest.xml file:

  • The INTERNET and ACCESS_FINE_LOCATION permissions (the latter for use with the MyLocationOverlay class, described later in this chapter)
  • Inside your <application>, a <uses-library> element with android:name = "com.google.android.maps", to indicate you are using one of the optional Android APIs

Here is the AndroidManifest.xml file for NooYawk:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"Images
 package="com.commonsware.android.maps">
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

  <application android:label="@string/app_name" android:icon="@drawable/cw">
    <uses-library android:name="com.google.android.maps"/>
    <activity android:name=".NooYawk" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
  </application>
  <supports-screens android:largeScreens="true" android:normalScreens="true"Images
 android:smallScreens="true" android:anyDensity="true"/>
</manifest>

That is pretty much all you need for starters, in addition to subclassing your activity from MapActivity. If you were to do nothing else, and built that project and tossed it in the emulator, you’d get a nice map of the world. Note, however, that MapActivity is abstract—you need to implement isRouteDisplayed() to indicate whether you are supplying some sort of driving directions. Since displaying driving directions is not supported by the current edition of the terms of service, you should have isRouteDisplayed() return false.

Optional Maps

While most mainstream Android devices have Google Maps, a small percentage do not, because their manufacturers did not elect to license it from Google. Therefore, you need to decide whether Google Maps is essential to your application’s operation.

If Google Maps is essential, then include the <uses-library> element in your application, as shown previously, as that will require any device running your app to have Google Maps.

If Google Maps isn’t essential, you can make it optional, via the android:required attribute available on <uses-library>. Set that to false, and Google Maps will be loaded into your application if it is available, but your application will run fine regardless. You will then need to use something like Class.forName("com.google.android.maps.MapView") to see if Google Maps is available to your application. If it is not, you can disable the menu items for it, or whatever would lead the user to your MapActivity.

NOTE: In older documentation, the android:required attribute was “undocumented” and its use and support was questionable. Google has now officially documented it, and it is available in Android 4.0 Ice Cream Sandwich and future releases.

Exercising Your Control

You can find your MapView widget by findViewById(), just as with any other widget. The widget itself then offers a getController() method. Between the MapView and MapController, you have a fair bit of capability to determine what the map shows and how it behaves. Zoom and center are two features you will likely want to use, so they are covered next.

Zoom

The map of the world you start with is rather broad. Usually, people looking at a map on a phone will be expecting something a bit narrower in scope, such as a few city blocks.

You can control the zoom level directly via the setZoom() method on the MapController. This takes an integer representing the level of zoom, where 1 is the world view and 21 is the tightest zoom you can get. Each level is a doubling of the effective resolution: 1 has the equator measuring 256 pixels wide, while 21 has the equator measuring 268,435,456 pixels wide. Since the phone’s display probably does not have 268,435,456 pixels in either dimension, the user sees a small map focused on one tiny corner of the globe. A level of 17 will show several city blocks in each dimension, which is probably a reasonable starting point for you to experiment with.

If you wish to allow users to change the zoom level, call setBuiltInZoomControls(true);, and the user will be able to zoom in and out of the map via zoom controls found at the bottom center of the map.

Center

Typically, you will need to control what the map is showing, beyond the zoom level, such as the user’s current location or a location saved with some data in your activity. To change the map’s position, call setCenter() on the MapController.

The setCenter() method takes a GeoPoint as a parameter. A GeoPoint represents a location, via latitude and longitude. The catch is that the GeoPoint stores latitude and longitude as integers representing the actual latitude and longitude in microdegrees (degrees multiplied by 1E6). This saves a bit of memory versus storing a float or double, and it greatly speeds up some internal calculations Android needs to do to convert the GeoPoint into a map position. However, it does mean you have to remember to multiply the real-world latitude and longitude by 1E6.

Layers Upon Layers

If you have ever used the full-size edition of Google Maps, you are probably used to seeing things overlaid atop the map itself, such as pushpins indicating businesses near the location being searched. In map parlance (and, for that matter, in many serious graphic editors), the pushpins are on a separate layer from the map itself, and what you are seeing is the composition of the pushpin layer atop the map layer.

Android’s mapping allows you to create layers as well, so you can mark up the maps as you need to based on user input and your application’s purpose. For example, NooYawk uses a layer to show where select buildings are located on the island of Manhattan.

Overlay Classes

Any overlay you want to add to your map needs to be implemented as a subclass of Overlay. There is an ItemizedOverlay subclass available if you are looking to add pushpins or the like; ItemizedOverlay simplifies this process.

To attach an overlay class to your map, just call getOverlays() on your MapView and add() your Overlay instance to it, as we do here with a custom SitesOverlay:

marker.setBounds(0, 0, marker.getIntrinsicWidth(),
                       marker.getIntrinsicHeight());

map.getOverlays().add(new SitesOverlay(marker));

We will look at that marker in the next section.

Drawing the ItemizedOverlay

As the name suggests, ItemizedOverlay allows you to supply a list of points of interest to be displayed on the map—specifically, instances of OverlayItem. The overlay, then, handles much of the drawing logic for you. Here are the minimum steps to make this work:

  1. Override ItemizedOverlay<OverlayItem> as your own subclass (in this example, SitesOverlay).
  2. In the constructor, build your roster of OverlayItem instances, and call populate() when they are ready for use by the overlay.
  3. Implement size() to return the number of items to be handled by the overlay.
  4. Override createItem() to return OverlayItem instances given an index.
  5. When you instantiate your ItemizedOverlay subclass, provide it with a Drawable that represents the default icon (e.g., a pushpin) to display for each item, on which you call boundCenterBottom() to enable the drop-shadow effect.

The marker from the NooYawk constructor is the Drawable used for step 5, which shows a pushpin.

For example, here is SitesOverlay:

private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
  private List<OverlayItem> items=new ArrayList<OverlayItem>();
  private Drawable marker=null;

  public SitesOverlay(Drawable marker) {
    super(marker);
    this.marker=marker;

    boundCenterBottom(marker);

    items.add(new OverlayItem(getPoint(40.748963847316034,
                                       -73.96807193756104),
                             "UN", "United Nations"));
    items.add(new OverlayItem(getPoint(40.76866299974387,
                                       -73.98268461227417),
                             "Lincoln Center",
                             "Home of Jazz at Lincoln Center"));
    items.add(new OverlayItem(getPoint(40.765136435316755,
                                       -73.97989511489868),
                             "Carnegie Hall",
            "Where you go with practice, practice, practice"));
    items.add(new OverlayItem(getPoint(40.70686417491799,
                                       -74.01572942733765),
                             "The Downtown Club",
                     "Original home of the Heisman Trophy"));

    populate();
  }

  @Override
  protected OverlayItem createItem(int i) {
    return(items.get(i));
  }

  @Override
  protected boolean onTap(int i) {
    Toast.makeText(NooYawk.this,
                    items.get(i).getSnippet(),
                    Toast.LENGTH_SHORT).show();

    return(true);
  }

  @Override
  public int size() {
    return(items.size());
  }
}

Handling Screen Taps

An Overlay subclass can also implement onTap(), to be notified when the user taps the map, so the overlay can adjust what it draws. For example, in full-size Google Maps, clicking a pushpin pops up a bubble with information about the business at that pin’s location. With onTap(), you can do much the same in Android.

The onTap() method for ItemizedOverlay receives the index of the OverlayItem that was tapped. It is up to you to do something worthwhile with this event.

In the case of SitesOverlay, as shown in the preceding section, onTap() looks like this:

@Override
protected boolean onTap(int i) {
  Toast.makeText(NooYawk.this,
                  items.get(i).getSnippet(),
                  Toast.LENGTH_SHORT).show();

  return(true);
}

Here, we just toss up a short Toast with the snippet from the OverlayItem, returning true to indicate we handled the tap.

My, Myself, and MyLocationOverlay

Android has a built-in overlay to handle two common scenarios:

  • Showing where you are on the map, based on GPS or other location-providing logic
  • Showing where you are pointed, based on the built-in compass sensor, where available

All you need to do is create a MyLocationOverlay instance, add it to your MapView’s list of overlays, and enable and disable the desired features at appropriate times.

The “at appropriate times” notion is for maximizing battery life. There is no sense in updating locations or directions when the activity is paused, so it is recommended that you enable these features in onResume() and disable them in onPause().

For example, NooYawk will display a compass rose using MyLocationOverlay. To do this, we first need to create the overlay and add it to the list of overlays (where me is the MyLocationOverlay instance as a private data member):

me=new MyLocationOverlay(this, map);
map.getOverlays().add(me);

Then, we enable and disable the compass rose as appropriate:

@Override
public void onResume() {
  super.onResume();

  me.enableCompass();
}

@Override
public void onPause() {
  super.onPause();

  me.disableCompass();
}

This gives us a compass rose while the activity is onscreen, as shown in Figure 40–1.

images

Figure 40–1. The NooYawk map, showing a compass rose and two OverlayItems

Rugged Terrain

Just as the Google Maps you use on your full-size computer can display satellite imagery, so too can Android maps.

MapView offers toggleSatellite(), which, as the name suggests, toggles on and off the satellite perspective on the area being viewed. You can allow the user to trigger this via an options menu or, in the case of NooYawk, via key taps:

 @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_S) {
      map.setSatellite(!map.isSatellite());
      return(true);
    }
    else if (keyCode == KeyEvent.KEYCODE_Z) {
      map.displayZoomControls(true);
      return(true);
    }

    return(super.onKeyDown(keyCode, event));
  }

Figure 40–2 shows a satellite view in NooYawk, courtesy of tapping the S key.

images

Figure 40–2. The NooYawk map, showing a compass rose and two OverlayItems, overlaid on the satellite view

Maps and Fragments

You might think that maps would be an ideal place to use fragments. After all, on a large tablet screen, you could allocate most of the space to the map but still have other stuff alongside it. Alas, over the last two major releases of Android, maps and fragments remain two great tastes that do not taste so great together.

First, MapView requires you to inherit from MapActivity. This has a few ramifications:

  • You cannot use the Android Compatibility Library (ACL), because that requires you to inherit from FragmentActivity, and Java does not support multiple inheritance. Hence, you can use maps in fragments only on Android 3.0 and higher, requiring that you fall back to some alternative implementation on older versions of Android.
  • Any activity that might host a map in a fragment has to inherit from MapActivity, even if in some cases it might not host a map in a fragment.

Also, MapView makes some assumptions about the timing of various events, in a fashion that makes setting up a map-based fragment a bit more complex than it might otherwise have to be.

It is entirely possible that someday these problems will be resolved, through a combination of an updated Google APIs Add-On for Android with fragment support, and possibly an updated ACL. In the meantime, here is the recipe for getting maps to work, as well as they can, in fragments.

Limit Yourself to the Latest Android Versions

In the manifest, make sure that you set both your android:minSdkVersion and your android:targetSdkVersion to at least 11, so your application runs only on Android 3.0 and newer. For example, here is the manifest from the Maps/NooYawkFragments sample project:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.commonsware.android.maps">
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

  <application android:label="@string/app_name"
              android:icon="@drawable/cw"
              android:hardwareAccelerated="true">
    <uses-library android:name="com.google.android.maps"/>
    <activity android:name=".NooYawk" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
  </application>
  <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="11" />
  <supports-screens android:largeScreens="true"
android:normalScreens="true" android:smallScreens="true" android:anyDensity="true"/>
</manifest>

Use onCreateView() and onActivityCreated()

A map-based fragment is simply a Fragment that shows a MapView. By and large, this code can look and work much like a MapActivity would, configuring the MapView, setting up an ItemizedOverlay, and so on.

However, there is a timing problem: you cannot reliably return a MapView widget, or an inflated layout containing such a widget, from onCreateView(). For whatever reason, it works fine the first time, but on a configuration change (e.g., screen rotation) it fails.

The solution is to return a container from onCreateView(), such as a FrameLayout, as shown here in the MapFragment class from NooYawkFragments:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
  return(new FrameLayout(getActivity()));
}

Then, in onActivityCreated()—once onCreate() has been completed in the hosting MapActivity—you can add a MapView to that container and continue with the rest of your normal setup:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);

  map=new MapView(getActivity(), "00yHj0k7_7vxbuQ9zwyXI4bNMJrAjYrJ9KKHgbQ");
  map.setClickable(true);

  map.getController().setCenter(getPoint(40.76793169992044,
                                        -73.98180484771729));
  map.getController().setZoom(17);
  map.setBuiltInZoomControls(true);

  Drawable marker=getResources().getDrawable(R.drawable.marker);

  marker.setBounds(0, 0, marker.getIntrinsicWidth(),
                         marker.getIntrinsicHeight());

  map.getOverlays().add(new SitesOverlay(marker));

  me=new MyLocationOverlay(getActivity(), map);
  map.getOverlays().add(me);

  ((ViewGroup)getView()).addView(map);
}

Note that we are creating a MapView in Java code, which means our Maps API key resides in the Java code (or something reachable from the Java code, such as a string resource). You could inflate a layout containing a MapView here if you wished—the change for MapFragment was simply to illustrate creating a MapView from Java code.

Host the Fragment in a MapActivity

You must make sure that whatever activity hosts the map-enabled fragment is a MapActivity. So, even though the NooYawk activity no longer has much to do with mapping, it must still be a MapActivity:

package com.commonsware.android.maps;

import android.os.Bundle;
import com.google.android.maps.MapActivity;

public class NooYawk extends MapActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  @Override
  protected boolean isRouteDisplayed() {
    return(false);
  }
}

The layout now points to a <fragment> instead of a MapView:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  class="com.commonsware.android.maps.MapFragment"
  android:id="@+id/map_fragment"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
/>

The resulting application, shown in Figure 40–3, looks like the original NooYawk activity would on a large screen, because we are not doing anything much else with the fragment system (e.g., having other fragments alongside in a landscape layout).

images

Figure 40–3. The NooYawkFragments map, rendered on a Motorola XOOM

A Custom Alternative for Maps and Fragments

The Android developer community was understandably frustrated at the limitations of maps within fragments, and grappled with the limitation of a MapView needing to be within a MapActivity. You can see the history of experimentation and discussion on the StackOverflow Android Developers forum, which led one of the contributors, Pete Doyle, to release the android-support-v4-googlemaps custom compatibility library.

Doyle’s custom compatibility library is a working solution to make FragmentActivity extend MapActivity. This in turn allows you to use a MapView object in a fragment.

You can download the support-v4-googlemaps custom compatibility library from GitHub at https://github.com/petedoyle/android-support-v4-googlemaps.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset