Android

com.google.android.maps.MapView

java.lang.Object
android.view.View Drawable.Callback KeyEvent.Callback
android.view.ViewGroup ViewManager ViewParent
com.google.android.maps.MapView

A View which displays a map. When focused, it will capture keypresses and touch gestures to pan and zoom the map. It can also be controlled programmatically (getController()) and can draw a number of Overlays on top of the map (getOverlays()).

The map can be displayed in a number of modes; see setSatellite(boolean), setTraffic(boolean), and setStreetView(boolean). It can optionally display a "reticle" when not it touch-mode, to aid in using pan-to-select; see setReticleDrawMode(MapView.ReticleDrawMode). It also draws a Google logo in the bottom-right corner.

The MapView is also a ViewGroup, with LayoutParameters allowing you to attach views either to a specific pixel offset, or to a specific latitude/longitude pair.

A MapView can only be constructed (or inflated) by a MapActivity. This is because it depends on threads which access the network and filesystem in the background; these threads must be shepherded by the lifecycle management in MapActivity. Tiles are cached on the filesystem in your application's directory. The cache is auto-managed so you don't need to do anything with it, and can delete it at any time.

In order to use a MapView in your app, you need to include the "android:apiKey" attribute in the MapView (or include a key in the MapView constructor). For now, just put any value there (e.g., "myapikey"). In order to run on actual devices, though, your application will need a real authentication key, but the process for issuing keys is not ready at this time.

XML attributes

See MapView Attributes, View Attributes

Nested Classes
MapView.LayoutParams Per-child layout information associated with MapView. 
MapView.ReticleDrawMode Allow the user to specify the mode in which the reticle is drawn. 

Summary

XML Attributes

Attribute name Related methods  
android:apiKey   An API Key required to use MapView. 
XML Attributes inherited from class android.view.ViewGroup
XML Attributes inherited from class android.view.View
Constants inherited from class android.view.ViewGroup
Constants inherited from class android.view.View
Fields inherited from class android.view.ViewGroup
Fields inherited from class android.view.View

Public Constructors

            MapView(Context context, String apiKey)
Constructs a MapView object.
            MapView(Context context, AttributeSet attrs)
Constructs a MapView object.
            MapView(Context context, AttributeSet attrs, int defStyle)
Constructs a MapView object.

Public Methods

          boolean  canCoverCenter()
Checks whether we currently have a map tile to cover the center of the map.
          void  computeScroll()
Captures scroll events and uses them to pan the map.
          void  displayZoomControls(boolean takeFocus)
Makes the zoom controls visible and optionally requests focus upon them so they can be accessed via keys.
          ViewGroup.LayoutParams  generateLayoutParams(AttributeSet attrs)
Returns a new set of layout parameters based on the supplied attributes set.
          MapController  getController()
Returns the MapController for this map, which you can use to control and animate pan and zoom.
          int  getLatitudeSpan()
The current latitude span (from the left edge to the right edge of the map) in decimal degrees multiplied by one million.
          int  getLongitudeSpan()
The current longitude span (from the top edge to the bottom edge of the map) in decimal degrees multiplied by one million.
          GeoPoint  getMapCenter()
Returns the current center-point position of the map, as a GeoPoint (latitude and longitude).
          int  getMaxZoomLevel()
Returns the maximum zoom level for the point currently at the center.
    final      List<Overlay getOverlays()
Access the overlay list.
          Projection  getProjection()
Get a projection for converting between screen-pixel coordinates and latitude/longitude coordinates.
          View  getZoomControls()
Returns a View containing a ZoomControls widget (i.e.
          int  getZoomLevel()
Returns the current zoom level of the map.
          boolean  isSatellite()
Checks whether the map is in "satellite" image mode.
          boolean  isStreetView()
Checks whether the map is drawing street view availability (blue outlines).
          boolean  isTraffic()
Checks whether the map is drawing traffic where available.
          void  onFocusChanged(boolean hasFocus, int direction, Rect unused)
Called by the view system when the focus state of this view changes.
          boolean  onKeyDown(int keyCode, KeyEvent event)
Passes keys to the overlays first, and if they don't handle them, try using them to pan.
          boolean  onKeyUp(int keyCode, KeyEvent event)
Passes keys to the overlays first, and if they don't handle them, try using them to pan.
          void  onRestoreInstanceState(Bundle state)
Restores the state of the MapView to a Bundle.
          void  onSaveInstanceState(Bundle state)
Saves the state of the MapView to a Bundle.
          boolean  onTouchEvent(MotionEvent ev)
Passes trackball events to the overlays first, and if they don't handle them, feed it to a gesture detector, and dispatch the detected gestures.
          boolean  onTrackballEvent(MotionEvent event)
Passes trackball events to the overlays first, and if they don't handle them, try using them to pan and "tap".
          void  onWindowFocusChanged(boolean hasFocus)
Called when the window containing this view gains or loses focus.
          void  preLoad()
Preload the tiles at the map's current center.
          void  setReticleDrawMode(MapView.ReticleDrawMode mode)
Specify how the reticle should be drawn when the device is not in touch mode.
          void  setSatellite(boolean on)
Sets the map mode to "satellite" mode, loading tiles of aerial imagery with roads and names superimposed.
          void  setStreetView(boolean on)
Control whether Street View availability (blue outlines) is shown on the map.
          void  setTraffic(boolean on)
Control whether traffic is shown on the map.

Protected Methods

          boolean  checkLayoutParams(ViewGroup.LayoutParams p)
Just checks if p instanceof MapView.LayoutParams.
          MapView.LayoutParams  generateDefaultLayoutParams()
Returns a set of layout parameters with a width of WRAP_CONTENT, a height of WRAP_CONTENT and with the coordinates (0, 0).
          ViewGroup.LayoutParams  generateLayoutParams(ViewGroup.LayoutParams p)
Returns a safe set of layout parameters based on the supplied layout params.
    final      void  onDraw(Canvas canvas)
The main draw method.
          void  onLayout(boolean changed, int left, int top, int right, int bottom)
Called from layout when this view should assign a size and position to each of its children.
    final      void  onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

          void  onSizeChanged(int w, int h, int oldw, int oldh)
This resizes the map object and repositions the reticle.
Methods inherited from class android.view.ViewGroup
Methods inherited from class android.view.View
Methods inherited from class java.lang.Object
Methods inherited from interface android.graphics.drawable.Drawable.Callback
Methods inherited from interface android.view.KeyEvent.Callback
Methods inherited from interface android.view.ViewManager
Methods inherited from interface android.view.ViewParent

Details

XML Attributes

android:apiKey

An API Key required to use MapView. Currently, this can be an arbitrary string. In order to run on actual devices, though, your app will need an authentic key, but the process for issuing keys is not ready at this time.

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol apiKey.

Related Methods

Public Constructors

public MapView(Context context, String apiKey)

Constructs a MapView object.

Parameters

context A MapActivity object.
apiKey A Google Maps API Key. For now, just put any value here (e.g., "myapikey"). In order to run on actual devices, though, your application will need a real authentication key, but the process for issuing keys is not ready at this time.

Throws

IllegalArgumentException if the enclosing context is not an instance of MapActivity.

public MapView(Context context, AttributeSet attrs)

Constructs a MapView object.

Parameters

context A MapActivity object.
attrs An attribute set; currently no attributes are used.

Throws

IllegalArgumentException if the enclosing context is not an instance of MapActivity.

public MapView(Context context, AttributeSet attrs, int defStyle)

Constructs a MapView object.

Parameters

context A MapActivity object.
attrs An attribute set; we currently have no attributes.
defStyle The default style to apply to this view. If 0, no style will be applied (beyond what is included in the theme). This may either be an attribute resource, whose value will be retrieved from the current theme, or an explicit style resource.

Throws

IllegalArgumentException if the enclosing context is not an instance of MapActivity, or if the attributes do not include an apiKey.

Public Methods

public boolean canCoverCenter()

Checks whether we currently have a map tile to cover the center of the map.

Returns

  • True if there is a tile for the center, false otherwise.

public void computeScroll()

Captures scroll events and uses them to pan the map.

public void displayZoomControls(boolean takeFocus)

Makes the zoom controls visible and optionally requests focus upon them so they can be accessed via keys.

Parameters

takeFocus If true, bring the zoom controls into focus. If false, do not bring controls into focus.

public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)

Returns a new set of layout parameters based on the supplied attributes set.

Parameters

attrs the attributes to build the layout parameters from

Returns

public MapController getController()

Returns the MapController for this map, which you can use to control and animate pan and zoom.

Returns

  • This map's MapController.

public int getLatitudeSpan()

The current latitude span (from the left edge to the right edge of the map) in decimal degrees multiplied by one million.

Returns

  • Latitude span in decimal degrees * 1,000,000.

public int getLongitudeSpan()

The current longitude span (from the top edge to the bottom edge of the map) in decimal degrees multiplied by one million.

Returns

  • Longitude span in decimal degrees * 1,000,000.

public GeoPoint getMapCenter()

Returns the current center-point position of the map, as a GeoPoint (latitude and longitude).

Returns

  • A GeoPoint of the map's center-point.

public int getMaxZoomLevel()

Returns the maximum zoom level for the point currently at the center. (Not all areas of the map offer the same high-res, close-up map tiles.) Takes into account whether satellite mode is enabled.

Returns

  • The maximum zoom level for the map's current center.

public final List<Overlay> getOverlays()

Access the overlay list. Any Overlays in this list will be drawn (in increasing order) and will receive events (in decreasing order, until one returns true). If you modify the list, you will probably want to call postInvalidate() so that the change will be made visible to the user.

Returns

  • The list of overlays. This has been run through synchronizedList(List); thus feel free to query it or modify it as you see fit and the changes will be reflected on the next draw or event. However, if you iterate over it, the entire loop should be enclosed in a block synchronizing on the list.

public Projection getProjection()

Get a projection for converting between screen-pixel coordinates and latitude/longitude coordinates.

Returns

  • The Projection of the map in its current state. You should not hold on to this object for more than one draw, since the projection of the map could change.

public View getZoomControls()

Returns a View containing a ZoomControls widget (i.e. +/- buttons). This view will become visible when the user starts panning the Map via touch and fade away if the user does not interact with it. The MapView handles this show and hide as appropriate, but the Activity is responsible for placing the controls on the screen. Using addView(View) is the common way to add this View to the screen.

Returns

  • A View with the ZoomControls.

public int getZoomLevel()

Returns the current zoom level of the map. At zoom level 1 (fully zoomed out), the equator of the earth is 256 pixels long. Each successive zoom level is magnified by a factor of 2.

Returns

  • The zoom level of the map.

public boolean isSatellite()

Checks whether the map is in "satellite" image mode.

Returns

  • True if in satellite image mode, false otherwise.

public boolean isStreetView()

Checks whether the map is drawing street view availability (blue outlines).

Returns

  • True if the map is drawing street view availability; false otherwise.

public boolean isTraffic()

Checks whether the map is drawing traffic where available.

Returns

  • True if the map is drawing traffic; false otherwise.

public void onFocusChanged(boolean hasFocus, int direction, Rect unused)

Called by the view system when the focus state of this view changes. Catch focus changed events to stop panning (since we might not get the keyUp anymore)

Parameters

hasFocus True if the View has focus; false otherwise.
direction The direction focus has moved when requestFocus() is called to give this view focus. Values are View.FOCUS_UP, View.FOCUS_DOWN, View.FOCUS_LEFT or View.FOCUS_RIGHT. It may not always apply, in which case use the default.
unused The rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will be null otherwise.

public boolean onKeyDown(int keyCode, KeyEvent event)

Passes keys to the overlays first, and if they don't handle them, try using them to pan.

Parameters

keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.

public boolean onKeyUp(int keyCode, KeyEvent event)

Passes keys to the overlays first, and if they don't handle them, try using them to pan.

Parameters

keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.

public void onRestoreInstanceState(Bundle state)

Restores the state of the MapView to a Bundle. Currently, this restores the center, zoomlevel, and state of the Zoom dialog.

Parameters

state The Bundle with the prior instance state.

public void onSaveInstanceState(Bundle state)

Saves the state of the MapView to a Bundle. Currently, this persists the center, zoomlevel, and state of the Zoom dialog.

Parameters

state The Bundle to maintain the current state.

public boolean onTouchEvent(MotionEvent ev)

Passes trackball events to the overlays first, and if they don't handle them, feed it to a gesture detector, and dispatch the detected gestures. It will always return false if this MapView is not isEnabled() or is not isClickable().

Parameters

ev The motion event.

Returns

  • True if the event was handled, false otherwise.

public boolean onTrackballEvent(MotionEvent event)

Passes trackball events to the overlays first, and if they don't handle them, try using them to pan and "tap".

Parameters

event The motion event.

Returns

  • True if the event was handled, false otherwise.

public void onWindowFocusChanged(boolean hasFocus)

Called when the window containing this view gains or loses focus. Catch focus changed events to stop panning (since we might not get the keyUp anymore).

Parameters

hasFocus True if the window containing this view now has focus, false otherwise.

public void preLoad()

Preload the tiles at the map's current center. This will begin fetching tiles.

public void setReticleDrawMode(MapView.ReticleDrawMode mode)

Specify how the reticle should be drawn when the device is not in touch mode.

Parameters

mode The reticle draw mode. Valid values are: DRAW_RETICLE_OVER - this is the default mode and in this mode the reticle will be drawn over all the overlays so it's always visible. DRAW_RETICLE_UNDER - the reticle will be drawn before all the overlays are drawn meaning the reticle is there but if any object is drawn at the same position it will cover the reticle. DRAW_RETICLE_NEVER - the reticle is not drawn

public void setSatellite(boolean on)

Sets the map mode to "satellite" mode, loading tiles of aerial imagery with roads and names superimposed. Note that this may change the zoom level when switching into map mode (if the current zoom is too high for map mode, the zoom is switched to the maximum map zoom).

Parameters

on If true, turn satellite tiles on. If false, turn regular map tiles on.

public void setStreetView(boolean on)

Control whether Street View availability (blue outlines) is shown on the map. This is incompatible with Traffic indicators, so they will be deactivated if necessary. Street View availability can be drawn over map tiles or over satellite tiles; however, they are optimized for map tiles.

Parameters

on If true, turn street view availability on. If false, turn them off.

public void setTraffic(boolean on)

Control whether traffic is shown on the map. This is incompatible with Street View indicators, so they will be deactivated if necessary. They can be drawn over map tiles or over satellite tiles; however, they are optimized for map tiles.

Parameters

on If true, turn traffic lines on. If false, turn them off.

Protected Methods

protected boolean checkLayoutParams(ViewGroup.LayoutParams p)

Just checks if p instanceof MapView.LayoutParams.

Parameters

p The LayoutParams object to verify.

Returns

  • True if p is an instance of MapView LayoutParams; false otherwise.

protected MapView.LayoutParams generateDefaultLayoutParams()

Returns a set of layout parameters with a width of WRAP_CONTENT, a height of WRAP_CONTENT and with the coordinates (0, 0).

Returns

  • a set of default layout parameters or null

protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p)

Returns a safe set of layout parameters based on the supplied layout params. When a ViewGroup is passed a View whose layout params do not pass the test of checkLayoutParams(android.view.ViewGroup.LayoutParams), this method is invoked. This method should return a new set of layout params suitable for this ViewGroup, possibly by copying the appropriate attributes from the specified set of layout params.

Parameters

p The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.

Returns

protected final void onDraw(Canvas canvas)

The main draw method. We draw the map background (loading tiles as appropriate), all our Overlays, the reticle (if desired), and the Google logo. We also update any panning animation currently underway.

Parameters

canvas the canvas on which the background will be drawn

protected void onLayout(boolean changed, int left, int top, int right, int bottom)

Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their their children.

Parameters

changed This is a new size or position for this view
left Left position, relative to parent
top Top position, relative to parent
right Right position, relative to parent
bottom Bottom position, relative to parent

protected final void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters

widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

protected void onSizeChanged(int w, int h, int oldw, int oldh)

This resizes the map object and repositions the reticle. If you override this method, be sure to call through to super.onSizeChanged().

Parameters

w Current width of this view.
h Current height of this view.
oldw Old width of this view.
oldh Old height of this view.
Copyright 2007 Google Inc. Build 0.9_r1-98467 - 14 Aug 2008 18:56