Wednesday, July 17, 2013

Creating a MapMarker to imitate XML Drawable - Maps V2

I spent a lot of time yesterday debugging why BitmapDescriptorFactory was throwing a null pointer exception all the time. After a while I realised it was only when I was using a Drawable I had created using XML, more specifically a layer-list with a shape and an item which has a Drawable. This should show up as a slightly translucent circle with an image on top, and works very fine when using it as a source for an ImageView. However, when trying to use it as Icon for a Marker with the new Google Maps v2 API, it just throws a null pointer exception, without much reason why :-(

So from here I have two choices, either create an image with the desired marker, or draw it programatically on a Bitmap Canvas. The first one is easy enough and I will not show that here, it is just a simple image you pop into the drawable folders in your Android project. The latter is way more fun and could be useful to you. The sample will be using Xamarin.Android to demonstrate how it is done there, however, it may be applicable to Java Android.

So first you need to know how big you want to have the marker to be.

In this case I just set it to 60dp, you can experiment with that. Now you have to do the drawing action.

Now that you have your BitmapDescriptor you can set it as an Icon for the map Marker.

There, done!