11

I use that Google Maps component MapView in an Android application. I can use the GPS location to show my location with a dot. But I would like to show an arrow instead, that points out the driving direction (bearing). I think that I can use the bearing value to get the angle of the arrow.

How can I do that?

Jonas
  • 121,568
  • 97
  • 310
  • 388

1 Answers1

19

Assuming you've got the Location then obtain the bearing by doing:

float myBearing = location.getBearing();

To implement the overlay you'll be using ItemizedOverlay and OverlayItem. You'll need to subclass OverlayItem to add the functionality to rotate the Drawable. Something like:

public BitmapDrawable rotateDrawable(float angle)
{
  Bitmap arrowBitmap = BitmapFactory.decodeResource(context.getResources(), 
                                                    R.drawable.map_pin);
  // Create blank bitmap of equal size
  Bitmap canvasBitmap = arrowBitmap.copy(Bitmap.Config.ARGB_8888, true);
  canvasBitmap.eraseColor(0x00000000);

  // Create canvas
  Canvas canvas = new Canvas(canvasBitmap);

  // Create rotation matrix
  Matrix rotateMatrix = new Matrix();
  rotateMatrix.setRotate(angle, canvas.getWidth()/2, canvas.getHeight()/2);

  // Draw bitmap onto canvas using matrix
  canvas.drawBitmap(arrowBitmap, rotateMatrix, null);

  return new BitmapDrawable(canvasBitmap); 
}

Then all that remains to be done is to apply this new Drawable to the OverlayItem. This is done using the setMarker() method.

Basel Darvish
  • 64
  • 2
  • 11
pheelicks
  • 7,461
  • 2
  • 45
  • 50
  • Shouldn't I extend [Overlay](http://code.google.com/intl/sv-SE/android/add-ons/google-apis/reference/com/google/android/maps/Overlay.html) instead, as [MyLocationOverlay](http://code.google.com/intl/sv-SE/android/add-ons/google-apis/reference/com/google/android/maps/MyLocationOverlay.html) does? – Jonas Dec 13 '10 at 12:31
  • 2
    This works nicely for me, but I had to change canvas.getWidth(), canvas.getHeight() to canvas.getWidth() / 2, canvas.getHeight() / 2 to rotate around the center of the image (or it gets rotated out of existence) – Gwyn Morfey Jan 17 '11 at 17:34
  • 1
    Just FYI - this solution to rotating a bitmap will resolve shrinking issues due to boundaries and rotating. (Search for "android rotate shrink") – Jeff Lamb Jun 09 '11 at 05:47
  • I have also found that this shrinks my image, anyone got a solution? – Lee Armstrong Jul 20 '11 at 06:36
  • @pheelicks Returning void, should be BitmapDrawable or Drawable – wi1 Nov 15 '14 at 21:14