Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Creating Overlays for a Google MapView

Published? false
FormatLanguage: WikiFormat

Problem:

Demarcating a point on a Google map using an image.

Solution:

Use the concept of Map Overlays.

Discussion:

Warning The Google Maps V1 API is deprecated; new code should use the V2 API discussed in Recipes 4285 and 4297.

Creating one's own map overlay is a 2 step process:

  1. Extend the Overlay class and implement the required functionality (the type and characteristics of the overlay) in that class.
  2. Another class which controls that Google map on the screen then instantiates the class that extends Overlay.
<source lang='java'>
 public class AddressOverlay extends Overlay
</source>

Constructor Initialization in the AddressOverlay class:
<source lang='java'>
public AddressOverlay(Context context, Address address, int drawable) {
	super();
	this.context=context;
	this.drawable=drawable;
	assert(null != address);
	this.setAddress(address);
	Double convertedLongitude = address.getLongitude() * 1E6;
	Double convertedLatitude = address.getLatitude() * 1E6;
	
	setGeopoint(new GeoPoint(
			convertedLatitude.intValue(),
			convertedLongitude.intValue()));
}

The draw() method of the Overlay class has to be overriden.

  @Override
	public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
		super.draw(canvas, mapView, shadow);
    	Point locationPoint = new Point();
    	Projection projection = mapView.getProjection();
    	projection.toPixels(getGeopoint(), locationPoint);
		
		// Reading the image
        Bitmap markerImage = BitmapFactory.decodeResource(context.getResources(), drawable);

        // Drawing the image, keeping the center of the image at the address's location
        canvas.drawBitmap(markerImage,locationPoint.x - markerImage.getWidth() / 2, locationPoint.y - markerImage.getHeight() / 2, null);
        return true;
     }

In the java class that is implementing the map View's function, the following lines of code are added to add an Overlay on the map:

	List<Overlay> mapOverlays = mapView.getOverlays();
	//Instantiating the AddressOverlay class we just defined
	//'androidmarker is the name of the image that you wish to place on the map
	AddressOverlay addressOverlay = new AddressOverlay(this, address, R.drawable.androidmarker); 
	//adding the overlay to the map
	mapOverlays.add(addressOverlay);
	mapView.invalidate();