Displaying marker at user input latitude and longitude in Google Maps Android API V2

May 9, 2013
By

In this article, we will develop an Android application which demonstrates how to display a marker in Google Maps Android API V2 corresponding to the user input latitude and longitude.



Unlike the application discussed in the article titled “Adding Marker at user input latitude and longitude in Google Map Android API V2“, here user input EditText widgets and Google Map are shown in the same activity.

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



1. Download and configure Google Play Services Library in Eclipse

Google Map for Android is now integrated with Google Play Services. So we need 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

Note : Please ensure that, the latest version of Google Play Service Library is installed


2. Create a new Android Application Project namely “LocationLatLngV2″

New Android Application Project

Figure 1 : New Android Application Project


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. Link to Google Play Services Library

Link Google Play Services library to this project

Figure 6 : Link 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 window, Click “Android Tools -> Add Support Library “

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


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Display Input Coordinates</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="str_hnt_lat">Enter Latitude</string>
    <string name="str_hnt_lng">Enter Longitude</string>

</resources>


11. Create a 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" >

    <EditText
        android:id="@+id/et_lat"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:hint="@string/str_hnt_lat" />

    <EditText
        android:id="@+id/et_lng"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:layout_below="@id/et_lat"
        android:hint="@string/str_hnt_lng" />

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/et_lng" />

</RelativeLayout>


12. Update the class MainActivity in the file src/in/wptrafficanalyzer/locationlatlngv2/MainActivity.java


package in.wptrafficanalyzer.locationlatlngv2;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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 {

    EditText etLng;
    EditText etLat;
    GoogleMap googleMap;

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

        // Reference to the EditText et_lat of the layout activity_main.xml
        etLat = (EditText)findViewById(R.id.et_lat);

        // Reference to the EditText et_lng of the layout activity_main.xml
        etLng = (EditText)findViewById(R.id.et_lng);

        etLng.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_DONE){

                    // Getting the entered latitude
                    String lat = etLat.getText().toString();

                    // Getting the entered longitude
                    String lng = etLng.getText().toString();

                    // Getting Google Play availability status
                    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

                    // Showing status
                    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

                        int requestCode = 10;
                        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getParent(), requestCode);
                        dialog.show();

                    }else { // Google Play Services are available

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

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

                        // Enabling MyLocation Layer of Google Map
                        googleMap.setMyLocationEnabled(true);

                        // LatLng object to store user input coordinates
                        LatLng point = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));

                        // Drawing the marker at the coordinates
                        drawMarker(point);
                    }
                }
                return false;
            }
        });
    }

    private void drawMarker(LatLng point){
        // Clears all the existing coordinates
        googleMap.clear();

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

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

        // Setting title for the InfoWindow
        markerOptions.title("Position");

        // Setting InfoWindow contents
        markerOptions.snippet("Latitude:"+point.latitude+",Longitude"+point.longitude);

        // Adding marker on the Google Map
        googleMap.addMarker(markerOptions);

        // Moving CameraPosition to the user input coordinates
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(point));

    }

    @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.locationlatlngv2"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

    <uses-permission android:name="in.wptrafficanalyzer.locationlatlngv2.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.locationlatlngv2.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 : Update “YOUR_ANDROID_API_KEY” at the line 43, with the Android API key obtained in Step 8.


14. Screenshots of the application

Inputing Latitude and Longitude

Figure 7 : Inputing Latitude and Longitude

Displaying user input latitude and longitude in Google Maps

Figure 8 : Displaying user input latitude and longitude in Google Maps


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

8 Responses to Displaying marker at user input latitude and longitude in Google Maps Android API V2

  1. D. thomas c on June 1, 2013 at 6:12 pm

    Firstly, great tutorial. For inquiry;
    How do you insert or where can you insert two displaying markers for the user input and measure the route for both of the coordinates? (using Json)

  2. Sathish Kumar on February 3, 2014 at 7:10 pm

    sir i need the code for draw the route map on google maps… the route source and destination entered by the user then only that map will be showed… i have already the code but it will automatically shows the google map… plz help me..

  3. Hussain Bharmal on April 14, 2014 at 6:52 pm

    Hello Sir,
    I have query regarding this tutorial. when I insert latitude and longitude and click on button the displays unfortunately stop. So whats the issue.

  4. Madhur on September 10, 2014 at 3:09 pm

    Hi,

    Really good tutorial, just need to know how can I zoom the map?

  5. Fabio on February 6, 2015 at 4:21 pm

    Good tutorial… I downloaded and compiled your code, I got the API key for maps, but when I launch it and enter latitude and longitude, no map is displayed.

    • Oli-Un-Nahar Asha on September 5, 2015 at 8:14 am

      Can you solve the problem?I have faced same type of problem.If you can solve the problem,please help me.

      • mahesh on November 23, 2015 at 12:36 pm

        we need to place the google play services location in android manifest

        then we need to create the new android xml file in values name as integer

        after creating the xml file u have to paste the below code

        6587000

  6. Shankar on April 25, 2015 at 11:50 pm

    Hey George.
    You have shared a very good tutorial on this blog. But i ve a problem.
    when i run the project and open the apk in AVD, the app crashes.
    What can i do?
    Please reply ASAP.

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