Adding marker on touched location of Google Maps using Android API V2 with SupportMapFragment

January 8, 2013
By

In this article, we will create an Android application which  adds a marker on the touched position of Google map. On taping the marker, the latitude and longitude will be displayed in a title box.

This Google Map application is developed using Google Map Android API V2.

We are making use SupportMapFragment to display Google Map in Android application.

This application is developed in Eclipse 4.2.1 with ADT plugin ( 21.0.0 ) and Android SDK ( 21.0.0 ). This application is tested in a real Android Phone with Android ( 2.3.6 ).


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 “LocationAtTouchedPositionV2″

Create a new Android Application Project

Figure 1 : Create a new Android Application Project


3. Configure Android Application Project

Configure Android Application Project

Figure 2 : Configure Android Application 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. Link to Google Play Service Library

Linking to Google Play Services Library

Figure 6 : Linking to 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.locationattouchedpositionv2"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

    </application>

</manifest>

Note : In the above code, replace “YOUR_API_KEY” with the api key, you generated in step 8.


11. Update the layout file res/layout/activity_main.xml to add SupportMapFragment


<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="wrap_content"
        android:layout_height="wrap_content"
    />
</RelativeLayout>

12. Update the file src/in/wptrafficanalyzer/locationattouchedpositionv2/MainActivity.java


package in.wptrafficanalyzer.locationattouchedpositionv2;

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

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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.MarkerOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap googleMap;

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

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

        // Getting a reference to the map
        googleMap = supportMapFragment.getMap();

        // Setting a click event handler for the map
        googleMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng latLng) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

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

                // Setting the title for the marker.
                // This will be displayed on taping the marker
                markerOptions.title(latLng.latitude + " : " + latLng.longitude);

                // Clears the previously touched position
                googleMap.clear();

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

                // Placing a marker on the touched position
                googleMap.addMarker(markerOptions);
            }
        });
    }

    @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;
    }
}


13. Screenshot of the Google Map in Action


Screenshot of the application in Execution

Figure 7 : Screenshot of the application in Execution


14. 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 Adding marker on touched location of Google Maps using Android API V2 with SupportMapFragment

  1. AYAN SINHA on January 9, 2013 at 7:37 pm

    hi your source code which I have downloaded and its not working it says can;t find class SupportmapFragment class. It was such a long time was finding to get a pop up but still i can see a failure in me. Please help if possible.

    And last but not the least your tutorials are really great

    • george on January 9, 2013 at 8:12 pm

      Hi,

      Please ensure the following :

      => The latest version of Android Support Library is included in the project.

      => The application is running in a real device containing Google Play Store with at least Android 2.2 or above.

      => The application is linked with Google Play Services Library

      • AYAN SINHA on January 10, 2013 at 12:10 pm

        Hi george,

        Have linked my code with google-play-services library but still it is not working. And now i am tensed because i dnt want to use map balloon overlay jars. Its simple but yet so difficult to get it. Plz help george.

  2. Sam on August 17, 2013 at 6:13 pm

    Hi george,

    I have linked my code with google play services library ,the android support library and also attained the api key from google Console. However my application was force closed when i test it.
    I am running on a 4.0.3 android device.
    Do you have any idea what else went wrong?

    • George Mathew on August 17, 2013 at 6:41 pm

      Hi,

      Please ensure that, “Android Private Libraries” is ticked in “Java Build Path -> Order and Export tab”

      After ticking the checkbox, do clean and build the project.

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