Customizing InfoWindow Contents in Google Map Android API V2 using InfoWindowAdapter

January 14, 2013
By

In this article we will create an Android application that displays a customized info-window in GoogleMap Android API V2 using InfoWindowAdapter interface.

For developing this application, we are using Eclipse 4.2.1 with ADT plugin ( 21.0.0 ) and Android SDK ( 21.0.0 ) and testing in a real device with Android 2.3.6  ( GingerBread ).


1. Download and configure Google Play Services Library in Eclipse

Please follow the given below link to setup Google Play Service library in Eclipse.

http://developer.android.com/google/play-services/setup.html


2. Create a new Android Application Project namely “LocationCustomInfoContents”

Create a new Android application project titled "LocationCustomInfoContents"

Figure 1 : Create a new Android application project titled "LocationCustomInfoContents"


3. Configure Android Application Project

Configure the project

Figure 2 : Configure the project


4. Design Application Launcher Icon

Design application launcher icon

Figure 3 : Design application launcher icon


5. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


6. Enter Main Activity Details

Enter MainActivity Details

Figure 5 : Enter MainActivity Details


7. Add Google Play Services Library to this project

Add Google Play Services Library

Figure 6 : Add Google Play Services Library


8. Get the API key for Google Maps Android API v2

We need to get an API key from Google to use Google Maps in Android application. Please follow the given below link to get the API key for Google Maps Android API v2.

https://developers.google.com/maps/documentation/android/start


9. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup window, Click “Android Tools -> Add Support Library “

10. Update the file AndroidManfiest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationcustominfocontents"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <permission
        android:name="in.wptrafficanalyzer.locationcustominfocontents.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="in.wptrafficanalyzer.locationcustominfocontents.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.locationcustominfocontents.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="ENTER_YOUR_API_KEY_HERE"/>

    </application>
</manifest>


11. Update the file res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LocationCustomInfoContents</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <color name="bg_color">#ffffff</color>
</resources>

12. Update the layout file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>
</RelativeLayout>


13. Update the layout file res/layout/info_window_layout.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="vertical"
    android:background="@color/bg_color" >

    <TextView
        android:id="@+id/tv_lat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_lng"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


14. Update the file src/in/wptrafficanalyzer/locationcustominfocontents/MainActivity.java

package in.wptrafficanalyzer.locationcustominfocontents;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = mapFragment.getMap();

        // Setting a custom info window adapter for the google map
        googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {

            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker arg0) {

                // Getting view from the layout file info_window_layout
                View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

                // Getting the position from the marker
                LatLng latLng = arg0.getPosition();

                // Getting reference to the TextView to set latitude
                TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);

                // Getting reference to the TextView to set longitude
                TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);

                // Setting the latitude
                tvLat.setText("Latitude:" + latLng.latitude);

                // Setting the longitude
                tvLng.setText("Longitude:"+ latLng.longitude);

                // Returning the view containing InfoWindow contents
                return v;

            }
        });

        // Adding and showing marker while touching the GoogleMap
        googleMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng arg0) {
                // Clears any existing markers from the GoogleMap
                googleMap.clear();

                // Creating an instance of MarkerOptions to set position
                MarkerOptions markerOptions = new MarkerOptions();

                // Setting position on the MarkerOptions
                markerOptions.position(arg0);

                // Animating to the currently touched position
                googleMap.animateCamera(CameraUpdateFactory.newLatLng(arg0));

                // Adding marker on the GoogleMap
                Marker marker = googleMap.addMarker(markerOptions);

                // Showing InfoWindow on the GoogleMap
                marker.showInfoWindow();

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

14. Screenshot of the application in execution

Showing CustomInfoWindowContents in the Google Map

Figure 7 : Showing CustomInfoWindowContents in the Google Map


15. Download Source Code



How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , ,

15 Responses to Customizing InfoWindow Contents in Google Map Android API V2 using InfoWindowAdapter

  1. Zwan on February 15, 2013 at 8:04 pm

    Really nice guide, thanks!

  2. Zeeshan on February 28, 2013 at 12:49 pm

    Thank you Sir

  3. Brian on April 29, 2013 at 11:28 am

    How do you place multiple markers with unique text? for some reason when I make additional markers they all end up having the text from the most recent marker? If someone could explain that would be great.

    • george on April 29, 2013 at 3:59 pm

      Hi Brian,

      This type of strange behavior may be due to some bug in your code.

      We can make this application into a multiple marker application by removing the line “googleMap.clear()” ( see line 76 ) of the class “MainActivity”

  4. Sumesh on July 18, 2013 at 3:10 pm

    Please provide a tutorial for custom info window with buttons

  5. Adrian on July 22, 2013 at 6:24 pm

    Why is the info window not aligning correctly with the marker? The info windows is sitting slightly left of the marker in your screenshot.

    • george on July 22, 2013 at 7:56 pm

      This is a great observation. Actually i did not do any thing purposefully for that. But today, when i run this application ( after recompilation ) , the info window is sitting exactly at the center of the marker.

      • Adrian on July 22, 2013 at 8:06 pm

        I have implemented this code and on my HTC one device the info window is also sitting slightly to the left. All of my others devices have the info window centered above the marker correctly. Could this be something specific to the HTC one?

        • george on July 22, 2013 at 8:19 pm

          I don’t know the reason for this. Similar issue is found here.

          In the mean time, can you please ensure that, your application is linking to the latest version of Google Play Services library.

          • Adrian on July 22, 2013 at 9:14 pm

            Thanks for the info, I will monitor that bug and wait for a fix.

  6. Manish on August 28, 2013 at 6:14 pm

    Hi,

    I want to show image in infowindow.Using googleMap.setInfoWindowAdapter(new InfoWindowAdapter() it works.

    But problem is that it loads all images of all marker infowindow simenteneously.so it takes too much time to load.

    I want to load infowindow content of marker which is currently clicked, not all marker infowindow.

  7. Manish on September 4, 2013 at 12:08 pm

    Hi,

    I load dynamic image in infowindow on marker click event.When I click on marker first time image is not shown, but when I click on same marker second time,image is shown properly.In both time infowindow is opened.

    Please give me proper solution.

  8. Mukesh on January 31, 2014 at 2:08 pm

    Hi,

    I put button on custom info window and try to make it clickable, but the problem is that every where on info window i found click listener of info window even on click of button also ..

  9. dharshan on March 28, 2014 at 2:54 pm

    Hi George,

    I’m a fan of your blogs. it helped me alot to learn about google maps from your blog. In info window, i’m stucked with some problem hope you help me in solving it.

    i have 10 marker with different data. used for loop to put marker on map but the title and snippet are not in a proper format. so i used info window. but in info window its showing only last marker’s information only. how to solve this.?

  10. Jose Carlos Lopez on October 26, 2014 at 12:27 am

    Nice! thanks for your tutorial.

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner