Custom Marker Icon for Google Maps Android API V2

March 27, 2013
By

In this article, we will develop an Android application which shows a custom marker icon at the touched position of the Google Map. On long clicking the Google Map, all the existing markers will be cleared from the Google Map.



This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0) and tested in a real Android device (Android 2.3.6  -  GingerBread).


1. Create a new Android application project namely “LocationCustomMarkerMapV2″

Create new Android Application project namely "LocationCustomMarkerMapV2"

Figure 1 : Create new Android Application project namely "LocationCustomMarkerMapV2"


2. Configure the project

Configure the application project

Figure 2 : Configure the application project


3. Design application launcher icon

Design application launcher icon

Figure 3 : Design application launcher icon


4. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity details

Figure 5 : Enter MainActivity details


6. Download and configure Google Play Services Library in Eclipse

Google Map for Android is now integrated with Google Play Services. So we need to set up Google Play Service Library for developing Google Map application in Android.

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

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


7. Add Google Play Services Library to this project

Add Google Play Services library to this project

Figure 6 : Add Google Play Services library to this project


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 menu, Click “Android Tools -> Add Support Library “

10. 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>


11. Add the marker icon to the folder res/drawable

Download the given below file marker.png and copy to the folder res/drawable


12. Update the class “MainActivity” in the file src/in/wptrafficanalyzer/locationcustommarkermapv2/MainActivity.java


package in.wptrafficanalyzer.locationcustommarkermapv2;

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

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap map;

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

        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting reference to Google Map
        map = fm.getMap();

        // OnClick Event listener for the Google Map
        map.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

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

                // Setting position for the marker
                markerOptions.position(point);

                // Setting custom icon for the marker
                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));

                // Setting title for the infowindow
                markerOptions.title(point.latitude + ","+point.longitude);

                // Adding the marker to the map
                map.addMarker(markerOptions);
            }
        });

        // LongClick Event listener for the Google Map
        map.setOnMapLongClickListener(new OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng point) {
                // Clear all the markers from the Google Map
                map.clear();
            }
        });
    }

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


13. Update the file AndroidManifest.xml


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

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

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

    <uses-permission android:name="in.wptrafficanalyzer.locationcustommarkermapv2.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.locationcustommarkermapv2.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="YOUR_ANDROID_API_KEY"/>

        </application>
</manifest>

Note : Replace “YOUR_ANDROID_API_KEY” at line 42 with the API key obtained in the step 8. 



14. Screenshot of the application in execution

Showing custom marker icon at the touched location

Figure 7 : Showing custom marker icon at the touched location


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: , ,

5 Responses to Custom Marker Icon for Google Maps Android API V2

  1. cyberhagz on March 27, 2013 at 5:48 pm

    Thanks a lot for your tutorial.. :)
    This tutorial will be very helpful for me..

  2. michael on March 27, 2013 at 6:14 pm

    This marker has been successfully I created.

    I have data in mysql and i want to display data in a dialog marker on maps v2 ..

    What can you help me solve this problem?
    thanks a lot, sir ..

  3. vanchi on October 26, 2013 at 12:24 pm

    Hello sir i have developed an application to show route, distance, and travelling time between two location its working but i need to show all possible routes between the two location…..plz help me

  4. vinay on March 25, 2015 at 10:47 am

    I have implemented custom marker using google android map v2.It was running good on all device with default marker, but when i switched to custom marker then it start giving me blank screen on some mobile (HTC WILDFIRE).but still map is running good.what happens is with custom marker it does not show text which i give to marker.my custom marker xml file is below :

    and i have implemented it in java file like below :

    SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fp_map);
    map = fm.getMap();
    if(map != null){

    map.setIndoorEnabled(false);
    map.setOnCameraChangeListener(getCameraChangeListener());
    //add custom window here
    map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    @Override
    public View getInfoWindow(Marker marker) {
    return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
    View v = null;
    try {
    if(!marker.getTitle().equalsIgnoreCase(“diff”)) {
    try {
    v = getLayoutInflater().inflate(R.layout.info_window, null);
    TextView title = (TextView) v.findViewById(R.id.markerText1);
    TextView midMsg = (TextView) v.findViewById(R.id.markerText2);
    TextView BelowMsg1 = (TextView) v.findViewById(R.id.markerText3);
    TextView BelowMsg2 = (TextView) v.findViewById(R.id.markerText4);

    String[] data = marker.getSnippet().split(“\\|\\|”);
    title.setText(marker.getTitle());
    midMsg.setText(data[0]);
    BelowMsg1.setText(“check here:” + data[2]);
    BelowMsg2.setText(data[1] + “check here also”);
    return v;
    } catch (Exception e) {
    String error = e.getMessage();
    }
    } else {
    return null; //so that normal view can be generted.
    }
    } catch (Exception e){
    String error1 = e.getMessage();
    return null;
    }
    return v;
    }
    });

    }

    finally i add marker like below

    BitmapDescriptor loaded_icon;
    loaded_icon = BitmapDescriptorFactory.fromResource(R.drawable.smiley_f);
    map.addMarker((new MarkerOptions().position(new LatLng(Double.parseDouble(data[1]), Double.parseDouble(data[2])))
    .title(data[0])
    .snippet(data[5] + “||” + data[6] + “||” + data[7])
    .icon(loaded_icon)))
    .showInfoWindow();

    the above add marker code is in loop so different marker can be shown to user.Now my problem is for many user it is working like great but for some phone (Ex. HTC WILDFIRE) it is giving blank screen as marker with image which i mentioned in xml file.

    I also get below error, not sure if it related to above problem or not. This error start coming way before opening page of map.

    E/copybit? Error opening frame buffer errno=13 (Permission denied)

    W/Adreno200-EGLSUB? : updater_create_surface_state failed to open copybit, error: -13

    Did google but did not find helpful. Please help.Thanks in advance

    I tried to check openGL with below function

    private boolean detectOpenGLES20() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    ConfigurationInfo info = am.getDeviceConfigurationInfo();
    return (info.reqGlEsVersion >= 0×20000);
    }

    and this function giving me true reply.so how to check if marker will be shown or not?

  5. altaf on October 20, 2015 at 12:11 pm

    Thank you sir

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