Google Maps Android API v2 different operations

We have seen how to configure with Google Maps Android API v2 in our last Post.

In this post we will see how google api v2 is differ with google api ver1 in different operations.

1) Setting Zoom Controls

In API v1:
for setting zoom level & zoom control we used:

mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);


In API v2:
For zooming contorl you need to use following attribute.

CameraUpdateFactory.zoomTo(float) gives you a CameraUpdate that changes the zoom level to the given value.

So, firstly you need to implement a interface i.e OnCameraChangeListener to your FragmentActivity and
just override method: public void onCameraChange(CameraPosition arg0);

Then use following code in your activity for zooming control and setting zoom level.

googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
			
     public void onCameraChange(CameraPosition arg0) {
	googleMap.animateCamera(CameraUpdateFactory.zoomTo(8));
        googleMap.setOnCameraChangeListener(YourMapActivity.this);
      }
});


Why OnCameraChangeListener?
If you want to keep track of the camera position, you can use an OnCameraChangeListener which is set on the map by calling GoogleMap.setOnCameraChangeListener(OnCameraChangeListener). The listener will be notified when the camera changes with an onCameraChange(CameraPosition) callback. You can then obtain the target (latitude/longitude), zoom, bearing and tilt of the camera.

2) Adding Marker at certain point

In API v1:
In API v1, we used to do such tedious work like:

List<Overlay> mapOverlays = mapView.getOverlays();
//Drawable image as marker
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);


The constructor for HelloItemizedOverlay (your custom ItemizedOverlay) takes the Drawable in order to set the default marker for all overlay items.

Then we used to create a GeoPoint that defines the map coordinates for the first overlay item, and pass it to a new OverlayItem

GeoPoint point = new GeoPoint(19240000,-99120000);
OverlayItem overlayitem = new OverlayItem(point, "Hi, Vikas!", "I'm in India!");


The OverlayItem constructor accepts the GeoPoint location, a string for the item’s title, and a string for the item’s snippet text, respectively.

Then we used to add this OverlayItem to your collection in the HelloItemizedOverlay instance, then add the HelloItemizedOverlay to the MapView:

itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);


In API v2:
add default marker to certain position.

static final LatLng Pune = new LatLng(18.500486, 73.866899);
Marker pune = mMap.addMarker(new MarkerOptions()
                          .position(Pune)
                          .title("Pune")
                          .snippet("Population: 54,137,400")
                         .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));


It’s possible to customize the color of the default marker image by passing a BitmapDescriptor object to the icon() method. You can use a set of predefined colors in the BitmapDescriptorFactory object, or set a custom marker color with the BitmapDescriptorFactory.defaultMarker(float hue) method. The hue is a value between 0 and 360, representing points on a color wheel.

If you’d like to change more than just the color of the marker, you can set a custom marker image, often called an icon. Custom icons are always set as a BitmapDescriptor, and defined using one of four methods in the BitmapDescriptorFactory class.

1) fromAsset(String assetName)
2) fromBitmap (Bitmap image)
3) fromFile (String path)
4) fromResource (int resourceId)

Ex.The below code creates a marker with a custom icon.

private static final LatLng Pune = new LatLng(18.500486, 73.866899);
  private Marker pune = mMap.addMarker(new MarkerOptions()
                            .position(Pune)
                            .title("Pune")
                            .snippet("Population: 54,137,400")
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));


3) Display my location Button on Google Maps Android API v2

To display my location on Google Maps Android API v2, call setMyLocationEnabled(true) method of the GoogleMap.

googleMap.setMyLocationEnabled(true);




4) Set map type of GoogleMap

To set the type of map tiles, call setMapType(int type) method of the GoogleMap.
Where type can be:
1) MAP_TYPE_NONE – No base map tiles.
2) MAP_TYPE_NORMAL – Basic maps
3) MAP_TYPE_SATELLITE – Satellite maps with no labels.
4) MAP_TYPE_HYBRID – Satellite maps with a transparent layer of major streets.
5) MAP_TYPE_TERRAIN – Terrain maps.

Example:

FragmentManager myFragmentManager = getSupportFragmentManager();
   SupportMapFragment mySupportMapFragment 
    = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
   googleMap = mySupportMapFragment.getMap();
   
   googleMap.setMyLocationEnabled(true);

   //googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
   //googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
   //googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
     googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);



5) Animate to certain position in Google Maps Android API v2

If you want animate to certain location/ point. You can use following snipplet.
In API v1:

GeoPoint point = new GeoPoint((int)(18.500486*1E6),(int)(73.866899*1E6)); 
 final MapController mc=mapView.getController();
 mc.animateTo(point);
 mc.setZoom(12);


In API v2:

final LatLng pos = new LatLng(18.500486, 73.866899);
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
		public void onCameraChange(CameraPosition arg0) {
			googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 13));
		}
    });


Using above code you can animate to given point with zoom level 13. If you want to keep track of the camera position, you can use an OnCameraChangeListener.

6) Adding Multiple points to Google maps

In API v1:
Suppose 5 pins added to a map.To keep all pins in view. we used define bounds to show multiple points in single view. i.e.

int minLat = 81 * MapStoresController.MAP_SCALE;
    int maxLat = -81 * MapStoresController.MAP_SCALE;
    int minLon = 181 * MapStoresController.MAP_SCALE;
    int maxLon = -181 * MapStoresController.MAP_SCALE;

    for (int i = 0; i < overlayItems.size(); i++) {
        Store s = overlayItems.getItem(i).getStore();
        minLat = (int) ((minLat > (s.getLocation().getLatitude() * MapStoresController.MAP_SCALE)) ? s.getLocation().getLatitude() * MapStoresController.MAP_SCALE :    minLat);
        maxLat = (int) ((maxLat < (s.getLocation().getLatitude() * MapStoresController.MAP_SCALE)) ? s.getLocation().getLatitude() * MapStoresController.MAP_SCALE : maxLat);
        minLon = (int) ((minLon > (s.getLocation().getLongitude() * MapStoresController.MAP_SCALE)) ? s.getLocation().getLongitude() * MapStoresController.MAP_SCALE : minLon);
        maxLon = (int) ((maxLon < (s.getLocation().getLongitude() * MapStoresController.MAP_SCALE)) ? .getLocation().getLongitude() * MapStoresController.MAP_SCALE : maxLon);
    }

    GeoPoint gp = controller.getUserLocation();

    minLat = (minLat > gp.getLatitudeE6()) ? gp.getLatitudeE6() : minLat;
    maxLat = (maxLat < gp.getLatitudeE6()) ? gp.getLatitudeE6() : maxLat;
    minLon = (minLon > gp.getLongitudeE6()) ? gp.getLongitudeE6() : minLon;
    maxLon = (maxLon < gp.getLongitudeE6()) ? gp.getLongitudeE6() : maxLon;

    mapView.getController().zoomToSpan((maxLat - minLat), (maxLon - minLon));
    mapView.getController().animateTo(new GeoPoint((maxLat + minLat) / 2, (maxLon + minLon) / 2));


In API v2:
Where as in API v2 we don not need to do such tedious job. Here you need to include your latitude and longitude in LatLngBounds.Builder. i.e

final LatLngBounds.Builder builder = new LatLngBounds.Builder();
//Number of latitude and longitude in for loop
for(;;){
final LatLng pos = new LatLng(lat,lng);
 builder.include(pos);
googleMap.addMarker(new MarkerOptions()
    		            .position(pos)
    		            .title("title")
    		            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}



Then animate camera with lat,lng and zoom level. It will show all markers in single view.

googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
				
				public void onCameraChange(CameraPosition arg0) {
					googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 50);
					googleMap.setOnCameraChangeListener(null);
				}
			});


7) Info Window in Google Map API V2

An info window allows you to display information to the user when

they tap on a marker on a map.

Default Info Window:
For creating default info window, you just need to add marker and set title or snipplet.


static final LatLng Pune = new LatLng(18.500486, 73.866899);
Marker pune = mMap.addMarker(new MarkerOptions()
                          .position(Pune)
                          .title("Pune")
                          .snippet("Population: 54,137,400")
                         .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));


So on click of marker it will show:




Custom Info Window using InfoWindowAdapter
To do this, you must create a concrete implementation of the InfoWindowAdapter interface and then call GoogleMap.setInfoWindowAdapter() with your implementation.

The interface contains two methods for you to implement: getInfoWindow(Marker) and getInfoContents(Marker).
So below is the xml: define in /res/layout/custom_info_contents.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_launcher"/>
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12dp"
            android:textStyle="bold"/>
        <TextView
            android:id="@+id/snippet"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10dp"/>
    </LinearLayout>

</LinearLayout>



Then in your Activity:

 googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
			
			@Override
			public View getInfoWindow(Marker arg0) {
				
				return null;
			}
			
			@Override
			public View getInfoContents(Marker marker) {
				View myContentsView = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
				 TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
		            tvTitle.setText(marker.getTitle());
		            TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
		            tvSnippet.setText(marker.getSnippet());
				return myContentsView;
			}
		});


In getInfoContents() inflate the xml. and you are done.



And Finally on click of info window you can go to next screen or you can display what you want to.

googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
				
				@Override
				public void onInfoWindowClick(Marker marker) {
				 //action to be taken after click on info window	
				}
			});


17 thoughts on “Google Maps Android API v2 different operations

  1. nice tutorial…thanx a lot…very helpful…post new tutorial of google map v2 which shows map route too while clicking on any of the balloon..

  2. Great tutorial. Any ideas about adding more custom data to the InfoWindow? E.g. apart from population I would like to display more data

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>