Google Geocoding API in Android Studio

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:
 
 
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.    
  12.     <TextView  
  13.             android:id="@+id/lat"  
  14.             android:layout_width="fill_parent"  
  15.             android:layout_height="wrap_content"  
  16.             android:textColor="#43bd00"  
  17.             android:textSize="16sp"  
  18.             android:textStyle="bold"  
  19.             android:paddingTop="6dip"  
  20.             android:paddingBottom="2dip"  
  21.                 />  
  22.     <TextView  
  23.            android:id="@+id/lng"  
  24.            android:layout_width="fill_parent"  
  25.            android:layout_height="wrap_content"  
  26.            android:paddingBottom="2dip">  
  27.     </TextView>  
  28.   </LinearLayout>  
  29. </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.      
  3. import android.app.Activity;    
  4. import android.content.Context;    
  5. import android.content.Intent;    
  6. import android.os.Bundle;    
  7. import android.view.View;    
  8. import android.widget.Button;    
  9. import android.widget.EditText;    
  10.      
  11. public class Search extends Activity {    
  12.     EditText enter;    
  13.     Button b;    
  14.     String place;    
  15.     final Context context=this;    
  16.     @Override    
  17.     protected void onCreate(Bundle savedInstanceState) {    
  18.         super.onCreate(savedInstanceState);    
  19.         setContentView(R.layout.search_layout);    
  20.         enter=(EditText)findViewById(R.id.enter);    
  21.         b=(Button)findViewById(R.id.search);    
  22.         b.setOnClickListener(new View.OnClickListener() {    
  23.             @Override    
  24.             public void onClick(View v) {    
  25.                 Intent i=new Intent(context,MainActivity.class);    
  26.                 place=enter.getText().toString();    
  27.                 i.putExtra("place",place);    
  28.                 startActivity(i);    
  29.      
  30.             }    
  31.         });    
  32.     }    
  33. }   
Step 5
 
Create one more Java class. Name this file "JSONParsering" and add the following code to it:
  1. package com.chhavi.googlegeocodingapi;  
  2.    
  3. import android.util.Log;  
  4.    
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.StatusLine;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpGet;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.json.JSONArray;  
  14. import org.json.JSONException;  
  15. import org.json.JSONObject;  
  16. import java.io.BufferedReader;  
  17. import java.io.IOException;  
  18. import java.io.InputStream;  
  19. import java.io.InputStreamReader;  
  20. import java.io.UnsupportedEncodingException;  
  21.    
  22. public class JSONParsering {  
  23.    
  24.     static InputStream input = null;  
  25.     static JSONObject jobj = null;  
  26.     static String json = "";  
  27.     public JSONParsering() {  
  28.     }  
  29.    
  30.     public JSONObject getJSONFromUrl(String url) {  
  31.    
  32.         try {  
  33.             DefaultHttpClient req = new DefaultHttpClient();  
  34.             HttpPost httpPost = new HttpPost(url);  
  35.             HttpResponse res = req.execute(httpPost);  
  36.             HttpEntity entity = res.getEntity();  
  37.             input = entity.getContent();  
  38.    
  39.         } catch (UnsupportedEncodingException e) {  
  40.             e.printStackTrace();  
  41.         } catch (ClientProtocolException e) {  
  42.             e.printStackTrace();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.    
  47.         try {  
  48.             BufferedReader read = new BufferedReader(new InputStreamReader(  
  49.                     input, "iso-8859-1"), 8);  
  50.             StringBuilder builderonj = new StringBuilder();  
  51.             String line = null;  
  52.             while ((line = read.readLine()) != null) {  
  53.                 builderonj.append(line + "\n");  
  54.             }  
  55.             input.close();  
  56.             json = builderonj.toString();  
  57.         } catch (Exception e) {  
  58.             Log.e("Buffer Reader""Error...... " + e.toString());  
  59.         }  
  60.    
  61.         try {  
  62.             jobj = new JSONObject(json);  
  63.         } catch (JSONException e) {  
  64.             Log.e("Parser""Error while parsing... " + e.toString());  
  65.         }  
  66.         return jobj;  
  67.     }  

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.    
  3. import android.app.ListActivity;  
  4. import android.app.ProgressDialog;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.os.AsyncTask;  
  8. import android.os.Bundle;  
  9. import android.util.Log;  
  10. import android.view.Menu;  
  11. import android.widget.ListAdapter;  
  12. import android.widget.ListView;  
  13. import android.widget.SimpleAdapter;  
  14.    
  15. import org.json.JSONArray;  
  16. import org.json.JSONException;  
  17. import org.json.JSONObject;  
  18.    
  19. import java.util.ArrayList;  
  20. import java.util.HashMap;  
  21.    
  22. public class MainActivity extends ListActivity {  
  23.    
  24.     private Context context;  
  25.      
  26.     private static String url="http://maps.googleapis.com/maps/api/geocode/json?address=";  
  27.     private static final String TAG_RESULTS="results";  
  28.     private static final String TAG_ADDRESS_COMPONENTS="address_components";  
  29.    
  30.     private static final String TAG_LONG_NAME="long_name";  
  31.     private static final String TAG_SHORT_NAME="short_name";  
  32.     private static final String TAG_TYPES="types";  
  33.    
  34.     private static final String TAG_FRORMATTED_ADDRESS="formatted_address";  
  35.    
  36.     private static final String TAG_GEOMETRY="geometry";  
  37.    
  38.     private static final String TAG_LOCATION="location";  
  39.    
  40.     private static final String TAG_LAT="lat";  
  41.     private static final String TAG_LNG="lng";  
  42.    
  43.     private static final String TAG_LOCATION_TYPE="location_type";  
  44.    
  45.     private static final String TAG_VIEW_PORT="view_port";  
  46.    
  47.     private static final String TAG_NORTHEAST="north_east";  
  48.    
  49.     private static final String TAG_SOUTHWEST="south_west";  
  50.    
  51.     private static final String TAG_STREET_ADDRESS="street_address";  
  52.     private static final String TAG_STATUS="status";  
  53.    
  54.     ArrayList<HashMap<String, String>> jlist = new ArrayList<HashMap<String, String>>();  
  55.     ListView listv ;  
  56.     JSONArray results;  
  57.    
  58.     @Override  
  59.     protected void onCreate(Bundle savedInstanceState) {  
  60.         super.onCreate(savedInstanceState);  
  61.         setContentView(R.layout.activity_main);  
  62.    
  63.         Intent intent = getIntent();  
  64.         String enter= intent.getStringExtra("place");  
  65.         Log.i("place..",enter+"");  
  66.         url=url+enter+"&sensor=false";  
  67.         new Progress(MainActivity.this).execute();  
  68.     }  
  69.    
  70.     private class Progress extends AsyncTask<String, Void, Boolean> {  
  71.         private ProgressDialog dialog;  
  72.    
  73.         public Progress(ListActivity activity) {  
  74.    
  75.             Log.i("class progress""constructor");  
  76.             context = activity;  
  77.             dialog = new ProgressDialog(context);  
  78.         }  
  79.    
  80.         private Context context;  
  81.    
  82.         protected void onPreExecute() {  
  83.             this.dialog.setMessage("Searching latitude and longitude");  
  84.             this.dialog.show();  
  85.         }  
  86.    
  87.         @Override  
  88.         protected void onPostExecute(final Boolean success) {  
  89.             if (dialog.isShowing()) {  
  90.                 dialog.dismiss();  
  91.             }  
  92.    
  93.             Log.i("jasonlist",jlist.size()+"");  
  94.             ListAdapter ad = new SimpleAdapter(context, jlist,R.layout.list_layout, new String[] { TAG_LAT, TAG_LNG }, new int[] { R.id.lat, R.id.lng });  
  95.             setListAdapter(ad);  
  96.             listv = getListView();  
  97.         }  
  98.    
  99.         protected Boolean doInBackground(final String... args) {  
  100.    
  101.             JSONParsering jParser = new JSONParsering();  
  102.             JSONObject jsonobj = jParser.getJSONFromUrl(url);  
  103.    
  104.            try {  
  105.                results = jsonobj.getJSONArray(TAG_RESULTS);  
  106.                if(results==null)  
  107.                {  
  108.                    HashMap<String, String> hmap = new HashMap<String, String>();  
  109.                    hmap.put("TAG_LAT","Null");  
  110.                    hmap.put("TAG_LNG","Null");  
  111.                }  
  112.                else  
  113.                {  
  114.                for(int i = 0; i < results.length(); i++)  
  115.                {  
  116.                    JSONObject c = results.getJSONObject(i);  
  117.                    JSONObject geometry = c.getJSONObject(TAG_GEOMETRY);  
  118.                    JSONObject location = geometry.getJSONObject(TAG_LOCATION);  
  119.    
  120.                    Log.i("check",location.toString());  
  121.                    double lat=location.getDouble(TAG_LAT);  
  122.                    double lng=location.getDouble(TAG_LNG);  
  123.    
  124.                    String latS=Double.toString(lat);  
  125.                    String lngS=Double.toString(lng);  
  126.    
  127.                    HashMap<String, String> hmap = new HashMap<String, String>();  
  128.                    Log.i("check",latS+"");  
  129.                    hmap.put(TAG_LAT, "LATITUDE: "+latS + "");  
  130.                    hmap.put(TAG_LNG,"LONGITUDE: "+lngS+"");  
  131.    
  132.                    jlist.add(hmap);  
  133.                }  
  134.                }  
  135.               }  
  136.    
  137.            catch(JSONException e)  
  138.            {  
  139.                 e.printStackTrace();  
  140.            }  
  141.             return null;  
  142.         }  
  143.     }  
  144.    
  145.     @Override  
  146.     public boolean onCreateOptionsMenu(Menu menu) {  
  147.         // Inflate the menu; this adds items to the action bar if it is present.  
  148.         getMenuInflater().inflate(R.menu.main, menu);  
  149.         return true;  
  150.     }  

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.    
  6.   <uses-permission android:name="android.permission.INTERNET"/>  
  7.    
  8.   <uses-sdk  
  9.       android:minSdkVersion="7"  
  10.       android:targetSdkVersion="16" />  
  11.    
  12.   <application  
  13.       android:allowBackup="true"  
  14.       android:icon="@drawable/ic_launcher"  
  15.       android:label="@string/app_name"  
  16.       android:theme="@style/AppTheme" >  
  17.     <activity  
  18.         android:name=".Search"  
  19.         android:label="@string/app_name" >  
  20.       <intent-filter>  
  21.         <action android:name="android.intent.action.MAIN" />  
  22.    
  23.         <category android:name="android.intent.category.LAUNCHER" />  
  24.       </intent-filter>  
  25.     </activity>  
  26.    
  27.     <activity  
  28.             android:name=".MainActivity"  
  29.             android:label="Parsing" />  
  30.    
  31.   </application>  
  32. </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 :) 


Similar Articles