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″
3. Configure Android Application Project
4. Design Application Launcher Icon
5. Create a blank activity
6. Enter Main Activity Details
7. Link to Google Play Service 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
15. Download Source Code







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.
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.
Thanks for your reply. I see now. You mean “the anonymous implementation of OnClickListener”. I read Android Development API Guide again and found this document at http://developer.android.com/guide/topics/ui/ui-events.html . Thanks a lot again.
Thank you for sharing this.
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
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.
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…
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
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
Google Map Android API V1 is deprecated as of Dec 03rd, 2012 and from March 03rd, 2013 we can’t request for new keys.
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…
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
i m done with lasst error
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?
Please check the logcat to get a hint on the issue.
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..
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.
Please see the given below article :
Selecting Google Place from AutoCompleteTextView and marking in Google Map Android API V2
Hi,
Can you do a small demo on, how to bring 3d view in Google map ApiV2.. Thanks in Advance
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.
especially to ICS and Jelly Bean..
sir when ever i will run above code it showing Null pointer exception in onpostExecute() method..
Excellent Tutorial…
Thanks a LOT
hello,
it s very interesting
good!!!
can you know how to ad a auto zoom ??
thanks
chris
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.
Hi,
Are you getting any error message in Logcat of Eclipse?
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!
sorry, i am not able to reproduce the error
hi,Sir
thanks for your tutorial
but I have a question
when I press find location
it always show No location found
I found out this is problem with emulator
Thanks.
when i press to find button; aplication is closing and give me this error unfortunatelly LocationGeocodingV2 stopped
how can i fix it ?
Paste your logcat error here
05-02 14:31:44.968: E/Google Maps Android API(16834): Failed to load map. Could not contact Google servers.
my new logcat error :
05-02 14:38:47.100: E/AndroidRuntime(17614): at dalvik.system.NativeStart.main(Native Method)
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 )
i tried this but error is same
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?
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));
}
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
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.
not working boss pls update……
the same problem, sir
Dear Jack,
Are you getting any error in logcat?
It just shows no location found, sir
I input the same place as you did in this article, but it does not work.
I tested the application, but did not see any issue
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?
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
Please ensure that, the locationName[0] and user input values are same.
In between, can you tell me the location you entered ?
Yeah. I’ve checked them and they are the same.
I entered the ‘malapuram’ as you did in the article.
all thanks for your tutorial, but I want to ask you how to show and hide edittext and button on click menu