Android Geocoding – Showing User Input Location on Google Map Android API V2

January 10, 2013
By

In this article, we will create an Android application which facilitates users to input street address in an EditText and on clicking the find button, application draws corresponding location marker on the Google Map Android API v2 using Google’s Geocoder API.

This application is an upgraded version of the application discussed in the article titled “Android Geocoding – Showing User Input Location on Google Map” where the location is shown in Google Map Android API v1.

This application is developed in Eclipse 4.2.1 with ADT plugin ( 21.0.0 ) and Android SDK ( 21.0.0 ) and is tested in a real Android Phone 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 “LocationGeocodingV2″

Create new Android application project

Figure 1 : Create 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 Main Activity Details

Figure 5 : Enter Main Activity Details


7. Link to Google Play Service Library

Link to Google Play Services Library

Figure 6 : Link 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.locationgeocodingv2"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

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

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_find"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/str_btn_find"
            android:layout_alignParentRight="true" />

        <EditText
            android:id="@+id/et_location"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:hint="@string/hnt_et_location"
            android:layout_toLeftOf="@id/btn_find" />

    </RelativeLayout>

    <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" />

</LinearLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LocationGeocodingV2</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="str_btn_find">Find</string>
    <string name="hnt_et_location">Enter location</string>
</resources>

13. Update the file src/in/wptrafficanalyzer/locationgeocodingv2/MainActivity.java

package in.wptrafficanalyzer.locationgeocodingv2;

import java.io.IOException;
import java.util.List;

import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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 {

    GoogleMap googleMap;
    MarkerOptions markerOptions;
    LatLng latLng;

    @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();

        // Getting reference to btn_find of the layout activity_main
        Button btn_find = (Button) findViewById(R.id.btn_find);

        // Defining button click event listener for the find button
        OnClickListener findClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Getting reference to EditText to get the user input location
                EditText etLocation = (EditText) findViewById(R.id.et_location);

                // Getting user input location
                String location = etLocation.getText().toString();

                if(location!=null && !location.equals("")){
                    new GeocoderTask().execute(location);
                }
            }
        };

        // Setting button click event listener for the find button
        btn_find.setOnClickListener(findClickListener);

    }

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

    // An AsyncTask class for accessing the GeoCoding Web Service
    private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{

        @Override
        protected List<Address> doInBackground(String... locationName) {
            // Creating an instance of Geocoder class
            Geocoder geocoder = new Geocoder(getBaseContext());
            List<Address> addresses = null;

            try {
                // Getting a maximum of 3 Address that matches the input text
                addresses = geocoder.getFromLocationName(locationName[0], 3);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return addresses;
        }

        @Override
        protected void onPostExecute(List<Address> addresses) {

            if(addresses==null || addresses.size()==0){
                Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
            }

            // Clears all the existing markers on the map
            googleMap.clear();

            // Adding Markers on Google Map for each matching address
            for(int i=0;i<addresses.size();i++){

                Address address = (Address) addresses.get(i);

                // Creating an instance of GeoPoint, to display in Google Map
                latLng = new LatLng(address.getLatitude(), address.getLongitude());

                String addressText = String.format("%s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getCountryName());

                markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title(addressText);

                googleMap.addMarker(markerOptions);

                // Locate the first location
                if(i==0)
                    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }
    }
}


14. Screenshot of the application in execution

Showing Street Address in Google Map Android API V2

Figure 7 : Showing Street Address in Google Map Android API V2


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

64 Responses to Android Geocoding – Showing User Input Location on Google Map Android API V2

  1. James on January 23, 2013 at 3:07 pm

    Thanks a lot in advance for providing your good tutorial. I tested your tutorial and it works fine. But in your code, I have a question about the code lines from 46 to 63 in your MainActivity in #13. Is it correct Android grammar to set onClickListener, ie. “OnClickListener findClickListener = new OnClickListener() {” ? Why don’t you set OnClickListener to the Button ? Please let me know that. BTW, your tutorial works fine and is a good tutorial.

    • george on January 23, 2013 at 3:53 pm

      Thank you for such a nice comment.

      >>Is it correct Android grammar to set onClickListener, ie. “OnClickListener findClickListener = new OnClickListener() {” ?

      Sure, this is correct. Here we are defining the listener in a variable and later this variable is passed as argument to the method setOnClickListener() of the button. This is just a coding style, that is all.

      An alternative to this is to use, as you specified, anonymous listener which can be defined as argument to the method setOnClickListener(). That is also correct.

  2. Zeeshan on February 25, 2013 at 12:27 pm

    Thank you for sharing this.

  3. HaarDik SolankI on March 2, 2013 at 2:11 am

    I tried this code run on my emulator..but it is not working there…

    it shows this app wont run wid out google play services..which are missing from yr phone….i got link to get google play services there..
    but it is not working there…

    and pls let me know how to sort it out…Thnk U Sir

    • george on March 2, 2013 at 5:22 am

      Google Map Android API V2 needs Google Play Services which in turn needs Google Play Store to install. Since Google Play store is not available with emulators, Android applications containing Google Map Android API V2 can not run in emulators.

      • HaarDik SolankI on March 2, 2013 at 8:54 pm

        Thnk u So much Sir…..Suppose i have 2 different layout…
        in one i wnt to set edit box and button ..and in another i want only mapview…. and if i write any location name in edit box as i click on button…..my app shud be navigated to another layout which is my mapview…and there i wnt to show location which i had written my previous layout’s edit box…can u pls post source code for that here???
        Thank u Sir…

        • george on March 2, 2013 at 10:32 pm

          An outline for implementing your requirement is given below :

          1. Create first activity with EditText and Button
          2. Create second activity with Google Map
          3. On Button click event listener, create an intent to second activity with location as the extra data.
          4. The extra data can be set using the method putExtra() of the Intent object.
          5. Start the second activity using the method startActivity()
          6. In the second activity, get the location using the method getIntent().getStringExtra().
          7. Now we got the location in the second activity. Remaining steps are same as this article.

          Hope this will do for you

          • HaarDik SolankI on March 3, 2013 at 12:42 am

            Thank u Sir.but prblm is i wnt to develope app using google api key v1….can u pls explain me regarding google api key v1..??
            Thank U Sir

          • george on March 3, 2013 at 5:09 am

            Google Map Android API V1 is deprecated as of Dec 03rd, 2012 and from March 03rd, 2013 we can’t request for new keys.

  4. HaarDik SolankI on March 3, 2013 at 11:44 am

    Oh but i have the key ..and i have made many activites now i m one step behind to be done ….thats y m asking u sir….i am making application for college project….Pls sir help me out…m in trouble…Thank U Sir for replying…

    • HaarDik SolankI on March 3, 2013 at 10:04 pm

      Sir..

      When i attempt to run above code for Google map v2..it says android library projects cant be launched…help me out…!!!

      Thank U Sir

  5. HaarDik SolankI on March 3, 2013 at 10:07 pm

    i m done with lasst error

  6. HaarDik SolankI on March 4, 2013 at 12:24 am

    Hey Sir I tried to run this code on my friend’s galaxy grand..it is showing map..but when i click on the button ..app stops working…wht shud be the prblm?

    • george on March 4, 2013 at 5:14 am

      Please check the logcat to get a hint on the issue.

  7. HaarDik SolankI on March 4, 2013 at 11:51 pm

    Thank U So muCh Sir…It is working now…..I had use android api bulid target instead of google api taarget…

    In above code it shows the location on map..but is it possible to show it with postal code of same input location ???

    Thank u once again sir..

  8. ShaRic19 on March 5, 2013 at 3:40 am

    Can you implement a sample geocoder in Maps API v2 that will show the results in an autocomplete textbox? Once one of the result is tap, it will be the only marker that will be shown in the map. Thanks. I’ll give some donations if you can do this favor.

  9. Rathish on March 25, 2013 at 2:08 pm

    Hi,
    Can you do a small demo on, how to bring 3d view in Google map ApiV2.. Thanks in Advance

  10. imam nur on March 26, 2013 at 10:19 pm

    Thanks for your tutorials..

    I want to ask you, how if the find button is replaced by the search menu action bar?
    because I think if you use a text field and a button, the screen will look small on the map. :P
    especially to ICS and Jelly Bean..

  11. bharath on April 1, 2013 at 3:37 pm

    sir when ever i will run above code it showing Null pointer exception in onpostExecute() method..

  12. Ahsan Feroz on April 3, 2013 at 8:03 pm

    Excellent Tutorial…
    Thanks a LOT

  13. chris on April 8, 2013 at 2:54 am

    hello,
    it s very interesting
    good!!!

    can you know how to ad a auto zoom ??

    thanks
    chris

  14. Arvind on April 12, 2013 at 1:40 am

    Hello Sir,
    I tried this tutorial.
    I found that service not available warning.
    I not able find location and null pointer exception arries.

    Can you help me why this happen.
    I do same like this tutorial still not get output.

    • george on April 12, 2013 at 5:29 am

      Hi,
      Are you getting any error message in Logcat of Eclipse?

  15. Érico on April 15, 2013 at 9:31 pm

    Hello. Thanks in advance for this great tutorial.
    I think i’m having the same problem that other people claimed here.

    My app has no errors, but when launched i write an address and press the find button and nothing happens.

    in logcat, i get this in red:

    “PID:8539 APP:com.google.android.gms TAG:Icing LOGMESSAGE:Aborting indexing of corpus 50E879CD5B52F133E3BDCB3EF9E83871FCA6DECE”

    Thanks for considerating my help request.
    PEACE!

    • george on April 16, 2013 at 6:02 am

      sorry, i am not able to reproduce the error

  16. ROY on April 25, 2013 at 7:25 am

    hi,Sir
    thanks for your tutorial
    but I have a question
    when I press find location
    it always show No location found

    • ROY on April 25, 2013 at 1:14 pm

      I found out this is problem with emulator
      Thanks.

  17. atasoy on May 2, 2013 at 4:33 pm

    when i press to find button; aplication is closing and give me this error unfortunatelly LocationGeocodingV2 stopped
    how can i fix it ?

    • george on May 2, 2013 at 4:45 pm

      Paste your logcat error here

      • atasoy on May 2, 2013 at 4:59 pm

        05-02 14:31:44.968: E/Google Maps Android API(16834): Failed to load map. Could not contact Google servers.

      • atasoy on May 2, 2013 at 5:08 pm

        my new logcat error :

        05-02 14:38:47.100: E/AndroidRuntime(17614): at dalvik.system.NativeStart.main(Native Method)

        • george on May 2, 2013 at 5:47 pm

          Please try the following :

          => Uninstall this application from your Android device

          => Clean this project ( In Eclipse IDE, use the menu Project -> Clean … )

          => Run the application ( In Eclipse IDE, use the menu Run -> Run As -> Android Application )

          • atasoy on May 2, 2013 at 5:59 pm

            i tried this but error is same

  18. Ganesh on May 4, 2013 at 1:22 am

    Hi all thanks for your tutorial, I am marking locations of near by some x radius of given lat and lng using place search google api’s. the problem i got was i was unable to mark all the near by locations which I am getting through place search api. only the last location in the list is being marked it seems. here is code where I am marking

    for(int i=0;i<nearlist.size();i++)
    {
    lnaddr=nearlist.get(i);
    LocA = new LatLng(lnaddr.getLat(), lnaddr.getLng());
    map.addMarker(new MarkerOptions().position(LocA).title(lnaddr.getAddrname()).snippet("Near by location").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
    }

    I am getting locations which are very near a part i mean they have a diff in their latitude and longtitde of .01xxx value.

    does this cause to make a single mark of all those positions? If so, please tell me any one here could help me. how can I solve this problem?

  19. immran on May 16, 2013 at 4:33 pm

    Hi
    I am getting a null pointer exception in this line. Can you explain me why?

    for(int i=0;i 0 ? address.getAddressLine(0) : “”,
    address.getCountryName());

    markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title(addressText);

    googleMap.addMarker(markerOptions);

    // Locate the first location
    if(i==0)
    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }

    • Ganesh on May 17, 2013 at 2:21 pm

      Dear friend, Can u please tell me what is address.getAddressLine(0) does and ur for loop seems diff from rest.

      Please tell me and also can u toast what is there in address.getAddressLine before for loop so that u cn know what exactly there in address object

  20. Deepthi on May 31, 2013 at 11:36 pm

    Hi sir,
    your tutorials are very much helping me. Thanks alot. I have copied your code but I’m getting error at lines 55 and 73. Is it the problem that class GeocoderTask was created after it was used in 55. plz help me sir. It is showing “GeocoderTask cannot be resolved” at line 55 and “Illegal modifier for the local class GeocoderTask; only abstract or final is permitted” at line 73.

  21. somish on June 3, 2013 at 10:27 am

    not working boss pls update……

    • Jack on June 4, 2013 at 4:16 pm

      the same problem, sir

      • george on June 4, 2013 at 4:40 pm

        Dear Jack,
        Are you getting any error in logcat?

        • Jack on June 4, 2013 at 4:47 pm

          It just shows no location found, sir

          • Jack on June 4, 2013 at 4:52 pm

            I input the same place as you did in this article, but it does not work.

          • george on June 4, 2013 at 5:43 pm

            I tested the application, but did not see any issue

          • Jack on June 4, 2013 at 6:26 pm

            Dear sir, I tried to run it in debug mode, and I found the addresses is equal to null. Does this mean something is wrong with my Google Maps Service?

          • Jack on June 4, 2013 at 7:09 pm

            In debug mode, everything goes well, but the function geocoder.getFromLocationName(locationName[0], 3)
            return nothing
            the locationName is OK
            Would you please give me some advice to solve this problem

          • george on June 4, 2013 at 7:55 pm

            Please ensure that, the locationName[0] and user input values are same.

            In between, can you tell me the location you entered ?

          • Jack on June 4, 2013 at 8:04 pm

            Yeah. I’ve checked them and they are the same.
            I entered the ‘malapuram’ as you did in the article.

  22. jonathan on June 13, 2013 at 10:44 am

    all thanks for your tutorial, but I want to ask you how to show and hide edittext and button on click menu

  23. Vijay on July 14, 2013 at 10:23 pm

    Hello Sir,
    I have tried this to run on Emulator,all is working well but this is showing “No Location Found” for every location I have searched.
    Please help what can be its cause?
    Thanks

    • george on July 14, 2013 at 10:30 pm

      Hi Vijay,
      Do you have any issue in a real Android device?
      Actually, i did not try this in emulators.

  24. febbie on July 20, 2013 at 4:14 pm

    Hi,
    I downloaded the source code but it didn’t work, I wonder why?
    It didn’t gave me any error, but when I run on my device, it didn’t show up

  25. Gaurav on August 3, 2013 at 8:00 am

    Hello Sir,

    There is no GeocoderTask in my android.location package.
    there is only a geocoder.class

    • george on August 3, 2013 at 8:26 am

      Hi Gaurav,

      GeocoderTask is a custom defined class in the MainActivity class for accessing the GeoCoding Web Service api.

  26. Dheemy on August 7, 2013 at 9:38 pm

    Hello ! nice tutorials! work so perfect! but can you tell me how i can mark only 1 place, the one that’s the closest to my location ? for example : my position longitude is mylong, and my position latitude is mylat? please help.. i am a newbie sir.. thx..

  27. Doloo on August 24, 2013 at 10:07 pm

    Hello, sir i implement all the steps it works fine shows map but when i enter the location in the textbox and hit find button the app restart and don’t go through the specified location.
    please tell me the solution…

  28. Nicolò on September 27, 2013 at 8:14 am

    Hi George,
    first thank you for the tutorial. It is very clear.
    But, despite i followed all the steps, i had some trouble.

    In fact, when there is no connection and i search for a location,
    the app crashes.

    In particular,there are 2 exceptions:
    -the IOexception of the istruction:
    “addresses=geocoder.getFromLocationName(locationName[0], 3)”
    is obviously catched, because the server does not respond;
    -another exception that i’m not able to catch, described by the messages in the logcat:
    “threadid=26: thread exiting with uncaught exception (group=0x41b0d438)” and “doTerminate failed: EGL count is 2 but managed count is 1″.

    Supposing the uncaught exception is thrown in the AsyncTask, i have tried to surround with try/catch the line
    “new GeocoderTask().execute(location)”;
    but i didn’t solve the problem.

    Sorry for my English.
    Thank you!

  29. Rajesh kumar B on December 31, 2013 at 11:43 am

    Hi George,
    The tutorial is very nice!!! thank you So much!!!

    Is it possible to find the near by places(Ex:Atm, Hospital) and the Location(Ex:Malapuram ) in the single Edit_Box search.

    if i give ATM it will show the near by atm of my current location, and if i type Coimbatore it will point to the coimbatore!!!

    Please Help Me!!!
    Thank you in Advance!!!

  30. raju on January 18, 2014 at 11:25 pm

    I trying to create sample app with Android Map V2. I tried serveral examples(downloaded from net), but none of them are working either showing blank map or throwing error. I tested on both device and emulator.

    I tried your code also and facing the same issue.

    Do you have any idea about this issue.

    Thanks,
    Raj

  31. Mahesh Falak on February 2, 2014 at 9:58 am

    Thanks your tutorial taught me lot much things about using google maps and its features and use in android…..
    But the problem I faced was that I m getting Error on
    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;
    classes…..
    So my whole project didnt work….Please help me

    • Muzamil on February 3, 2014 at 8:27 pm

      I guess you didn’t correctly configure google-play-service library in your project.

  32. Patrick on February 17, 2014 at 11:25 am

    Hi, I’m wondering can I put the search result on a list view instead of showing it on maps?

    I’m working on proximity alert project, and I want user to search the place to trigger the alarm and select it directly from the list.

    any helps are appreciated :)

  33. Bivas on March 28, 2014 at 11:58 am

    How can i load google api? and how can i get api key please suggest me 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