I'm upgrading an Android application from version 1 to version 2 of the android google maps API. In my version 1 code, I was able to draw text directly on the map in my subclass of ItemizedOverlay by overriding the draw() method, as follows. The text I want to draw is dynamic, an additional text item that I want to display next to each map marker, so the text will be added/removed frequently as different symbols are plotted / removed.
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
if (!shadow) {
canvas.drawText("some text", (float) point.x + TextOffsetX , (float) point.y + TextOffsetY, m_paint);
}
return super.draw(canvas, mapView, shadow, when);
}
However, this doesn't seem possible in the version 2 of the API. THere's isn't really a concept of ItemizedOverlays and nothing can be subclassed. Is there some way I can draw text on the GoogleMap in the new API version?
You can create a Marker from a View by using the following code:
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Source: http://www.nasc.fr/android/android-using-layout-as-custom-marker-on-google-map-api/
edit: If you use more than a single marker, make sure you don't do the DisplayMetrics and view setup stuff (everything above Bitmap bitmap =.....) for every marker. That would slow down your app dramatically.
I had the same problem, trying to upgrade from v1 to v2. Finally I used a marker, created a Bitmap with the text, and used it as icon of the marker.
First of all, you have to create de Bitmap with the text. Note: configure paintText with text properties (color, typeface, textalign,...)
Rect boundsText = new Rect();
paintText.getTextBounds(strText, 0, strText.length(), boundsText);
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmpText = Bitmap.createBitmap(boundsText.width(), boundsText.height(), conf);
Then, use Canvas for drawing the text. It is a little bit madness fix text with canvas dimenssion.
Canvas canvasText = new Canvas(bmpText);
canvasText.drawText(strText, canvasText.getWidth() / 2, canvasText.getHeight(), paintText);
Finally use Bitmap to create icon in MarkerOption
MarkerOptions markerOptions = new MarkerOptions()
.position(latlngMarker)
.icon(BitmapDescriptorFactory.fromBitmap(bmpText))
.anchor(0.5f, 1);
Hope it could help you.