Introduction

In this article, you will learn about the Google Geocoding API. Geocoding is the process of converting addresses into geographical coordinates (latitude and longitude). Reverse Geocoding is the process of converting geographic coordinates into a human-readable address. The Google Geocoding API provides a direct way to access these services via an HTTP request.
A Geocoding API request has the following form: http://maps.googleapis.com/maps/api/geocode/output?parameters. In this article, we will do Geocoding using JSON output.
The Geocoding request being used by me is:
http://maps.googleapis.com/maps/api/geocode/json?address=place name entered&sensor=false
Step 1
Go to "Layout" -> "New" -> "Layout resource file". Name this file "search_layout" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="vertical"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#ffdbac">
  6. <EditText
  7. android:id="@+id/enter"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:textSize="20dp"
  11. android:hint="Enter the required Location...."
  12. android:layout_marginTop="40dp"
  13. android:layout_marginLeft="20dp"
  14. android:layout_marginRight="20dp"/>
  15. <Button
  16. android:id="@+id/search"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:layout_marginLeft="130dp"
  20. android:layout_marginTop="40dp"
  21. android:text="Search"
  22. android:background="@drawable/button_lay"
  23. android:paddingRight="10dp"
  24. android:paddingLeft="10dp"
  25. />
  26. </LinearLayout>
The layout looks like:
im1.jpg
This layout has been designed to allow the user to enter the name of the required location.
Step 2
Open "activity_main" and add the following code to it:
  1. <ListView
  2. android:layout_marginTop="60dp"
  3. android:id="@android:id/list"
  4. android:layout_width="fill_parent"
  5. android:layout_height="wrap_content"
  6. android:scrollbars="vertical"/>
The layout looks like:
im2.jpg
Step 3
Create yet another layout file. Name it "list_layout" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="vertical"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#e2e3c8">
  6. <LinearLayout
  7. xmlns:android="http://schemas.android.com/apk/res/android"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:orientation="vertical">
  11. <TextView
  12. android:id="@+id/lat"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content"
  15. android:textColor="#43bd00"
  16. android:textSize="16sp"
  17. android:textStyle="bold"
  18. android:paddingTop="6dip"
  19. android:paddingBottom="2dip"
  20. />
  21. <TextView
  22. android:id="@+id/lng"
  23. android:layout_width="fill_parent"
  24. android:layout_height="wrap_content"
  25. android:paddingBottom="2dip">
  26. </TextView>
  27. </LinearLayout>
  28. </LinearLayout>
Step 4
Right-click on your package name the select "New" -> "Java class". Name this class "Search" and add the following code to it:
  1. package com.chhavi.googlegeocodingapi;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. public class Search extends Activity {
  10. EditText enter;
  11. Button b;
  12. String place;
  13. final Context context=this;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.search_layout);
  18. enter=(EditText)findViewById(R.id.enter);
  19. b=(Button)findViewById(R.id.search);
  20. b.setOnClickListener(new View.OnClickListener() {
  21. @Override
  22. public void onClick(View v) {
  23. Intent i=new Intent(context,MainActivity.class);
  24. place=enter.getText().toString();
  25. i.putExtra("place",place);
  26. startActivity(i);
  27. }
  28. });
  29. }
  30. }
Step 5
Create one more Java class. Name this file "JSONParsering" and add the following code to it:
  1. package com.chhavi.googlegeocodingapi;
  2. import android.util.Log;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.StatusLine;
  6. import org.apache.http.client.ClientProtocolException;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.impl.client.DefaultHttpClient;
  11. import org.json.JSONArray;
  12. import org.json.JSONException;
  13. import org.json.JSONObject;
  14. import java.io.BufferedReader;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.InputStreamReader;
  18. import java.io.UnsupportedEncodingException;
  19. public class JSONParsering {
  20. static InputStream input = null;
  21. static JSONObject jobj = null;
  22. static String json = "";
  23. public JSONParsering() {
  24. }
  25. public JSONObject getJSONFromUrl(String url) {
  26. try {
  27. DefaultHttpClient req = new DefaultHttpClient();
  28. HttpPost httpPost = new HttpPost(url);
  29. HttpResponse res = req.execute(httpPost);
  30. HttpEntity entity = res.getEntity();
  31. input = entity.getContent();
  32. } catch (UnsupportedEncodingException e) {
  33. e.printStackTrace();
  34. } catch (ClientProtocolException e) {
  35. e.printStackTrace();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. try {
  40. BufferedReader read = new BufferedReader(new InputStreamReader(
  41. input, "iso-8859-1"), 8);
  42. StringBuilder builderonj = new StringBuilder();
  43. String line = null;
  44. while ((line = read.readLine()) != null) {
  45. builderonj.append(line + "\n");
  46. }
  47. input.close();
  48. json = builderonj.toString();
  49. } catch (Exception e) {
  50. Log.e("Buffer Reader", "Error...... " + e.toString());
  51. }
  52. try {
  53. jobj = new JSONObject(json);
  54. } catch (JSONException e) {
  55. Log.e("Parser", "Error while parsing... " + e.toString());
  56. }
  57. return jobj;
  58. }
  59. }
This class returns the JSON object for the URL passed.
Step 6
Open "MainActivity" and add the following code to it:
  1. package com.chhavi.googlegeocodingapi;
  2. import android.app.ListActivity;
  3. import android.app.ProgressDialog;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.os.AsyncTask;
  7. import android.os.Bundle;
  8. import android.util.Log;
  9. import android.view.Menu;
  10. import android.widget.ListAdapter;
  11. import android.widget.ListView;
  12. import android.widget.SimpleAdapter;
  13. import org.json.JSONArray;
  14. import org.json.JSONException;
  15. import org.json.JSONObject;
  16. import java.util.ArrayList;
  17. import java.util.HashMap;
  18. public class MainActivity extends ListActivity {
  19. private Context context;
  20. private static String url="http://maps.googleapis.com/maps/api/geocode/json?address=";
  21. private static final String TAG_RESULTS="results";
  22. private static final String TAG_ADDRESS_COMPONENTS="address_components";
  23. private static final String TAG_LONG_NAME="long_name";
  24. private static final String TAG_SHORT_NAME="short_name";
  25. private static final String TAG_TYPES="types";
  26. private static final String TAG_FRORMATTED_ADDRESS="formatted_address";
  27. private static final String TAG_GEOMETRY="geometry";
  28. private static final String TAG_LOCATION="location";
  29. private static final String TAG_LAT="lat";
  30. private static final String TAG_LNG="lng";
  31. private static final String TAG_LOCATION_TYPE="location_type";
  32. private static final String TAG_VIEW_PORT="view_port";
  33. private static final String TAG_NORTHEAST="north_east";
  34. private static final String TAG_SOUTHWEST="south_west";
  35. private static final String TAG_STREET_ADDRESS="street_address";
  36. private static final String TAG_STATUS="status";
  37. ArrayList<HashMap<String, String>> jlist = new ArrayList<HashMap<String, String>>();
  38. ListView listv ;
  39. JSONArray results;
  40. @Override
  41. protected void onCreate(Bundle savedInstanceState) {
  42. super.onCreate(savedInstanceState);
  43. setContentView(R.layout.activity_main);
  44. Intent intent = getIntent();
  45. String enter= intent.getStringExtra("place");
  46. Log.i("place..",enter+"");
  47. url=url+enter+"&sensor=false";
  48. new Progress(MainActivity.this).execute();
  49. }
  50. private class Progress extends AsyncTask<String, Void, Boolean> {
  51. private ProgressDialog dialog;
  52. public Progress(ListActivity activity) {
  53. Log.i("class progress", "constructor");
  54. context = activity;
  55. dialog = new ProgressDialog(context);
  56. }
  57. private Context context;
  58. protected void onPreExecute() {
  59. this.dialog.setMessage("Searching latitude and longitude");
  60. this.dialog.show();
  61. }
  62. @Override
  63. protected void onPostExecute(final Boolean success) {
  64. if (dialog.isShowing()) {
  65. dialog.dismiss();
  66. }
  67. Log.i("jasonlist",jlist.size()+"");
  68. ListAdapter ad = new SimpleAdapter(context, jlist,R.layout.list_layout, new String[] { TAG_LAT, TAG_LNG }, new int[] { R.id.lat, R.id.lng });
  69. setListAdapter(ad);
  70. listv = getListView();
  71. }
  72. protected Boolean doInBackground(final String... args) {
  73. JSONParsering jParser = new JSONParsering();
  74. JSONObject jsonobj = jParser.getJSONFromUrl(url);
  75. try {
  76. results = jsonobj.getJSONArray(TAG_RESULTS);
  77. if(results==null)
  78. {
  79. HashMap<String, String> hmap = new HashMap<String, String>();
  80. hmap.put("TAG_LAT","Null");
  81. hmap.put("TAG_LNG","Null");
  82. }
  83. else
  84. {
  85. for(int i = 0; i < results.length(); i++)
  86. {
  87. JSONObject c = results.getJSONObject(i);
  88. JSONObject geometry = c.getJSONObject(TAG_GEOMETRY);
  89. JSONObject location = geometry.getJSONObject(TAG_LOCATION);
  90. Log.i("check",location.toString());
  91. double lat=location.getDouble(TAG_LAT);
  92. double lng=location.getDouble(TAG_LNG);
  93. String latS=Double.toString(lat);
  94. String lngS=Double.toString(lng);
  95. HashMap<String, String> hmap = new HashMap<String, String>();
  96. Log.i("check",latS+"");
  97. hmap.put(TAG_LAT, "LATITUDE: "+latS + "");
  98. hmap.put(TAG_LNG,"LONGITUDE: "+lngS+"");
  99. jlist.add(hmap);
  100. }
  101. }
  102. }
  103. catch(JSONException e)
  104. {
  105. e.printStackTrace();
  106. }
  107. return null;
  108. }
  109. }
  110. @Override
  111. public boolean onCreateOptionsMenu(Menu menu) {
  112. // Inflate the menu; this adds items to the action bar if it is present.
  113. getMenuInflater().inflate(R.menu.main, menu);
  114. return true;
  115. }
  116. }
The strings declared at the beginning of this class are some of the elements of the JSON document. I wanted to access the "lat" and "lng" elements in the location object. For reaching "lat" and "lng", the following parsing is required: JSON obj-> results (JSON array)-> JSON obj->geometry (JSON obj)-> location (JSON obj)-> lat and lng element.
Step 7
Finally, make the following changes in "AndroidManifest.xml":
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="com.chhavi.googlegeocodingapi"
  3. android:versionCode="1"
  4. android:versionName="1.0" >
  5. <uses-permission android:name="android.permission.INTERNET"/>
  6. <uses-sdk
  7. android:minSdkVersion="7"
  8. android:targetSdkVersion="16" />
  9. <application
  10. android:allowBackup="true"
  11. android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name"
  13. android:theme="@style/AppTheme" >
  14. <activity
  15. android:name=".Search"
  16. android:label="@string/app_name" >
  17. <intent-filter>
  18. <action android:name="android.intent.action.MAIN" />
  19. <category android:name="android.intent.category.LAUNCHER" />
  20. </intent-filter>
  21. </activity>
  22. <activity
  23. android:name=".MainActivity"
  24. android:label="Parsing" />
  25. </application>
  26. </manifest>
Output snapshots:
im3.jpg
On entering a location name:
im4.jpg
On clicking the search button:
im5.jpg
Final output:
im6.jpg
You can check if the displayed latitude and longitude values are correct or not from http://maps.googleapis.com/maps/api/geocode/json?address=PUNE&sensor=false
Thank you... Enjoy coding :)