Android – OverlayItem.setMarker(Drawable icon)
I’ve been developing in Android for a little over two months off and on and am finding certain things I really love and certain things I hate. This is one of the things I hate.
Android provides a nice class to manage drawing OverlayItems to a map called ItemizedOverlay; for instance you might want to display all the people in your contact list on a map. Well, you’d probably want to display a different icon for each person, right? OK, examine the API.
setMarkerpublic void setMarker(android.graphics.drawable.Drawable marker)
Sets the marker to be used when drawing this item on the map. Setting the marker to null will cause the default marker to be drawn (the marker is null by default, so you can just skip this, instead). The marker may be drawn using any combination of the null,
OK, that looks perfect. Go ahead and give each OverlayItem the Drawable icon you want to use. Look at the map and… wait a minute. Nothing shows up. Why is that? It works when you haven’t specified the marker…
Well, what this method fails to inform you is that you must define the bounds of a Drawable object before you use it on a map. The definition of Drawable says
The setBounds(Rect) method must be called to tell the Drawable where it is drawn and how large it should be. All Drawables should respect the requested size, often simply by scaling their imagery. A client can find the preferred size for some Drawables with the getIntrinsicHeight() and getIntrinsicWidth() methods.
So to solve the problem we must do the following:
Drawable icon = getResources().getDrawable(someicon); icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight()); personItem.setMarker(icon);
I wish that an icon defaulted to having its drawable bounds be the rectangle (0, 0, width, height), but you must explicitly define these bounds.