I am developing an Android Application where I'm using Google Map API v2. I need to show the user location on a map with custom markers.
Each marker will show the picture of the user from an URL. The image must be downloaded in asynchronous mode from the server. See the attached screenshot for an example.
How do I add an image and custom information in the marker?
In the Google Maps API v2 Demo there is a
MarkerDemoActivity class in which you can see how a custom Image is set to a GoogleMap.
// Uses a custom icon. mSydney = mMap.addMarker(new MarkerOptions() .position(SYDNEY) .title("Sydney") .snippet("Population: 4,627,300") .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
As this just replaces the marker with an image you might want to use a
Canvas to draw more complex and fancier stuff:
Bitmap.Config conf = Bitmap.Config.ARGB_8888; Bitmap bmp = Bitmap.createBitmap(80, 80, conf); Canvas canvas1 = new Canvas(bmp); // paint defines the text color, // stroke width, size Paint color = new Paint(); color.setTextSize(35); color.setColor(Color.BLACK); //modify canvas canvas1.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.user_picture_image), 0,0, color); canvas1.drawText("User Name!", 30, 40, color); //add marker to Map mMap.addMarker(new MarkerOptions().position(USER_POSITION) .icon(BitmapDescriptorFactory.fromBitmap(bmp)) // Specifies the anchor to be at a particular point in the marker image. .anchor(0.5f, 1));
This draws the Canvas
canvas1 onto the
GoogleMap mMap. The code should (mostly) speak for itself, there are many tutorials out there how to draw a
Canvas. You can start by looking at the Canvas and Drawables from the Android Developer page.
Now you also want to download a picture from an URL, assuming you know the URL you can get it with this piece of code:
URL url = new URL(user_image_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bmImg = BitmapFactory.decodeStream(is);
After that you can replace the
BitmapFactory.decodeResource(getResources(), R.drawable.user_picture_image) with the
bmImg. You also must download the image from an background thread (you could use
AsyncTask for that).