Tuesday 12 November 2013

Showing nearby places and place details using Google Places API and Google Maps Android API V2

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mapv2.demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />   
   
    <permission
        android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="com.mapv2.demo.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="com.mapv2.demo.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>
       
       
        <activity
            android:name="com.mapv2.demo.PlaceDetailsActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name=".PlaceDetails" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
       
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk"/>
       
       
       
    </application>

</manifest>

Step 4 :- Open 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" >
   
    <Spinner
        android:id="@+id/spr_place_type"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_alignParentTop="true" />
   
    <Button
        android:id="@+id/btn_find"
        android:layout_width="wrap_content"
        android:layout_height="60dp"       
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@id/spr_place_type"
        android:text="@string/str_btn_find" />   

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/spr_place_type"
        class="com.google.android.gms.maps.SupportMapFragment" />   
   
</RelativeLayout>


1.)  activity_place_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   
    <WebView
        android:id="@+id/wv_place_details"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"  />
   

</LinearLayout>


Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

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.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


public class MainActivity extends FragmentActivity implements LocationListener{
   
    GoogleMap mGoogleMap;   
    Spinner mSprPlaceType;   
   
    String[] mPlaceType=null;
    String[] mPlaceTypeName=null;
   
    double mLatitude=0;
    double mLongitude=0;
   
    HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
   
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       
       
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);       
       
        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);
       
        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
       
        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
       
        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
       
        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);
       
        Button btnFind;
       
        // Getting reference to Find Button
        btnFind = ( Button ) findViewById(R.id.btn_find);
       
       
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

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

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

        }else { // Google Play Services are available
           
            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                   
            // Getting Google Map
            mGoogleMap = fragment.getMap();
                   
            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);
           
           
           
            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location From GPS
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                    onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);
                       
            mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
               
                @Override
                public void onInfoWindowClick(Marker arg0) {
                    Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
                    String reference = mMarkerPlaceLink.get(arg0.getId());
                    intent.putExtra("reference", reference);
                   
                    // Starting the Place Details Activity
                    startActivity(intent);
                }
            });
           
           
           
            // Setting click event lister for the find button
            btnFind.setOnClickListener(new OnClickListener() {
               
                @Override
                public void onClick(View v) {   
                   
                   
                    int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                    String type = mPlaceType[selectedPosition];
                                       
                   
                    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                    sb.append("location="+mLatitude+","+mLongitude);
                    sb.append("&radius=5000");
                    sb.append("&types="+type);
                    sb.append("&sensor=true");
                    sb.append("&key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE");
                   
                   
                    // Creating a new non-ui thread task to download Google place json data
                    PlacesTask placesTask = new PlacesTask();                                   
                   
                    // Invokes the "doInBackground()" method of the class PlaceTask
                    placesTask.execute(sb.toString());
                   
                   
                }
            });
           
        }       
        
    }
   
    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);               
               

                // Creating an http connection to communicate with url
                urlConnection = (HttpURLConnection) url.openConnection();               

                // Connecting to url
                urlConnection.connect();               

                // Reading data from url
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }

                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }

        return data;
    }        

   
    /** A class, to download Google Places */
    private class PlacesTask extends AsyncTask<String, Integer, String>{

        String data = null;
       
        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                 Log.d("Background Task",e.toString());
            }
            return data;
        }
       
        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result){           
            ParserTask parserTask = new ParserTask();
           
            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
       
    }
   
    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

        JSONObject jObject;
       
        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String,String>> doInBackground(String... jsonData) {
       
            List<HashMap<String, String>> places = null;           
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();
       
            try{
                jObject = new JSONObject(jsonData[0]);
               
                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);
               
            }catch(Exception e){
                    Log.d("Exception",e.toString());
            }
            return places;
        }
       
        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String,String>> list){           
           
            // Clears all the existing markers
            mGoogleMap.clear();
           
            for(int i=0;i<list.size();i++){
           
                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();
               
                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);
   
                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));               
               
                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));
               
                // Getting name
                String name = hmPlace.get("place_name");
               
                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");
               
                LatLng latLng = new LatLng(lat, lng);
               
                // Setting the position for the marker
                markerOptions.position(latLng);
   
                // Setting the title for the marker.
                //This will be displayed on taping the marker
                markerOptions.title(name + " : " + vicinity);               
   
                // Placing a marker on the touched position
                Marker m = mGoogleMap.addMarker(markerOptions);               

                // Linking Marker id and place reference
                mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));               
              
           
            }       
           
        }
       
    }
   
   

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

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);
       
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
       
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
       
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
       
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub       
    }
}




1.)  PlaceDetailsActivity.java

package com.mapv2.demo;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

public class PlaceDetailsActivity extends Activity {
    WebView mWvPlaceDetails;
   
   
    protected void onCreate(Bundle savedInstanceState) {
       
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_place_details);
       
        // Getting reference to WebView ( wv_place_details ) of the layout activity_place_details
        mWvPlaceDetails = (WebView) findViewById(R.id.wv_place_details);
       
        mWvPlaceDetails.getSettings().setUseWideViewPort(false);
       
        // Getting place reference from the map   
        String reference = getIntent().getStringExtra("reference");
       
       
        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?");
        sb.append("reference="+reference);
        sb.append("&sensor=true");
        sb.append("&key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE");
       
       
        // Creating a new non-ui thread task to download Google place details
        PlacesTask placesTask = new PlacesTask();                                   
       
        // Invokes the "doInBackground()" method of the class PlaceTask
        placesTask.execute(sb.toString());   
       
    };
   
   
    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);               
               

                // Creating an http connection to communicate with url
                urlConnection = (HttpURLConnection) url.openConnection();               

                // Connecting to url
                urlConnection.connect();               

                // Reading data from url
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }

                data = sb.toString();
                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }

        return data;
    }        

   
    /** A class, to download Google Place Details */
    private class PlacesTask extends AsyncTask<String, Integer, String>{

        String data = null;
       
        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                 Log.d("Background Task",e.toString());
            }
            return data;
        }
       
        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result){           
            ParserTask parserTask = new ParserTask();
           
            // Start parsing the Google place details in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
    }
   
   
    /** A class to parse the Google Place Details in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, HashMap<String,String>>{

        JSONObject jObject;
       
        // Invoked by execute() method of this object
        @Override
        protected HashMap<String,String> doInBackground(String... jsonData) {
       
            HashMap<String, String> hPlaceDetails = null;
            PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
       
            try{
                jObject = new JSONObject(jsonData[0]);
               
                // Start parsing Google place details in JSON format
                hPlaceDetails = placeDetailsJsonParser.parse(jObject);
               
            }catch(Exception e){
                    Log.d("Exception",e.toString());
            }
            return hPlaceDetails;
        }
       
        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(HashMap<String,String> hPlaceDetails){           
           
           
            String name = hPlaceDetails.get("name");
            String icon = hPlaceDetails.get("icon");
            String vicinity = hPlaceDetails.get("vicinity");
            String lat = hPlaceDetails.get("lat");
            String lng = hPlaceDetails.get("lng");
            String formatted_address = hPlaceDetails.get("formatted_address");
            String formatted_phone = hPlaceDetails.get("formatted_phone");
            String website = hPlaceDetails.get("website");
            String rating = hPlaceDetails.get("rating");
            String international_phone_number = hPlaceDetails.get("international_phone_number");
            String url = hPlaceDetails.get("url");
           
           
            String mimeType = "text/html";
            String encoding = "utf-8";
           
            String data =     "<html>"+                           
                            "<body><img style='float:left' src="+icon+" /><h1><center>"+name+"</center></h1>" +
                            "<br style='clear:both' />" +
                            "<hr  />"+
                            "<p>Vicinity : " + vicinity + "</p>" +
                            "<p>Location : " + lat + "," + lng + "</p>" +
                            "<p>Address : " + formatted_address + "</p>" +
                            "<p>Phone : " + formatted_phone + "</p>" +
                            "<p>Website : " + website + "</p>" +
                            "<p>Rating : " + rating + "</p>" +
                            "<p>International Phone  : " + international_phone_number + "</p>" +
                            "<p>URL  : <a href='" + url + "'>" + url + "</p>" +           
                            "</body></html>";
           
            // Setting the data in WebView
            mWvPlaceDetails.loadDataWithBaseURL("", data, mimeType, encoding, "");           
        }
    }
}


2.)    PlaceDetailsJSONParser.java

package com.mapv2.demo;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

public class PlaceDetailsJSONParser {
   
    /** Receives a JSONObject and returns a list */
    public HashMap<String,String> parse(JSONObject jObject){       
       
        JSONObject jPlaceDetails = null;
        try {           
            /** Retrieves all the elements in the 'places' array */
            jPlaceDetails = jObject.getJSONObject("result");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaceDetails(jPlaceDetails);
    }
   
   
    /** Parsing the Place Detai12ls Object object */
    private HashMap<String, String> getPlaceDetails(JSONObject jPlaceDetails){
       
       
        HashMap<String, String> hPlaceDetails = new HashMap<String, String>();
       
        String name = "-NA-";
        String icon = "-NA-";
        String vicinity="-NA-";
        String latitude="";
        String longitude="";
        String formatted_address="-NA-";
        String formatted_phone="-NA-";
        String website="-NA-";
        String rating="-NA-";
        String international_phone_number="-NA-";
        String url="-NA-";
       
        try {
            // Extracting Place name, if available
            if(!jPlaceDetails.isNull("name")){
                name = jPlaceDetails.getString("name");
            }
           
            // Extracting Icon, if available
            if(!jPlaceDetails.isNull("icon")){
                icon = jPlaceDetails.getString("icon");
            }
           
            // Extracting Place Vicinity, if available
            if(!jPlaceDetails.isNull("vicinity")){
                vicinity = jPlaceDetails.getString("vicinity");
            }   
           
            // Extracting Place formatted_address, if available
            if(!jPlaceDetails.isNull("formatted_address")){
                formatted_address = jPlaceDetails.getString("formatted_address");
            }
           
            // Extracting Place formatted_phone, if available
            if(!jPlaceDetails.isNull("formatted_phone_number")){
                formatted_phone = jPlaceDetails.getString("formatted_phone_number");
            }   
           
            // Extracting website, if available
            if(!jPlaceDetails.isNull("website")){
                website = jPlaceDetails.getString("website");
            }   
           
            // Extracting rating, if available
            if(!jPlaceDetails.isNull("rating")){               
                rating = jPlaceDetails.getString("rating");
            }
           
            // Extracting rating, if available
            if(!jPlaceDetails.isNull("international_phone_number")){               
                international_phone_number = jPlaceDetails.getString("international_phone_number");
            }
           
            // Extracting url, if available
            if(!jPlaceDetails.isNull("url")){               
                url = jPlaceDetails.getString("url");
            }
           
            latitude = jPlaceDetails.getJSONObject("geometry").getJSONObject("location").getString("lat");
            longitude = jPlaceDetails.getJSONObject("geometry").getJSONObject("location").getString("lng");
           
           
            hPlaceDetails.put("name", name);
            hPlaceDetails.put("icon", icon);           
            hPlaceDetails.put("vicinity", vicinity);
            hPlaceDetails.put("lat", latitude);
            hPlaceDetails.put("lng", longitude);
            hPlaceDetails.put("formatted_address", formatted_address);
            hPlaceDetails.put("formatted_phone", formatted_phone);
            hPlaceDetails.put("website", website);
            hPlaceDetails.put("rating", rating);
            hPlaceDetails.put("international_phone_number", international_phone_number);
            hPlaceDetails.put("url", url);
           
        } catch (JSONException e) {           
            e.printStackTrace();
        }
               
        return hPlaceDetails;
    }
}


3.)  PlaceJSONParser.java

package com.mapv2.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PlaceJSONParser {
   
    /** Receives a JSONObject and returns a list */
    public List<HashMap<String,String>> parse(JSONObject jObject){       
       
        JSONArray jPlaces = null;
        try {           
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaces(jPlaces);
    }
   
   
    private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
        int placesCount = jPlaces.length();
        List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> place = null;   

        /** Taking each place, parses and adds to list object */
        for(int i=0; i<placesCount;i++){
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject)jPlaces.get(i));
                placesList.add(place);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
       
        return placesList;
    }
   
    /** Parsing the Place JSON object */
    private HashMap<String, String> getPlace(JSONObject jPlace){

        HashMap<String, String> place = new HashMap<String, String>();
        String placeName = "-NA-";
        String vicinity="-NA-";
        String latitude="";
        String longitude="";
        String reference="";
               
       
        try {
            // Extracting Place name, if available
            if(!jPlace.isNull("name")){
                placeName = jPlace.getString("name");
            }
           
            // Extracting Place Vicinity, if available
            if(!jPlace.isNull("vicinity")){
                vicinity = jPlace.getString("vicinity");
            }   
           
            latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
            longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
            reference = jPlace.getString("reference");
           
           
            place.put("place_name", placeName);
            place.put("vicinity", vicinity);
            place.put("lat", latitude);
            place.put("lng", longitude);
            place.put("reference", reference);
           
           
        } catch (JSONException e) {           
            e.printStackTrace();
        }       
        return place;
    }
}

Step 6 :- Run Code.




Step 7 :- Download Code :- https://dl.dropboxusercontent.com/u/109954727/Map/map30.zip

Android Tutorials Intents and Activities Applications ListView Applications Fragment Applications Menu Applications Android Action Bar Applications Android Action Bar Sherlock Applications Android tab applications GPS and Google Map Applications Chart (Graph) Applications Styles and Themes Applications Showing nearby places with photos at any location in Google Maps Android API V2

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mapv2.demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <permission
        android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="com.mapv2.demo.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="com.mapv2.demo.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="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk"/>
       
    </application>

</manifest>

Step 4 :- Open 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" >

    <Spinner
                android:id="@+id/spr_place_type"
                android:layout_width="wrap_content"
                android:layout_height="60dp"
                android:layout_alignParentTop="true" />

    <Button
                android:id="@+id/btn_find"
                android:layout_width="wrap_content"
                android:layout_height="60dp"           
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@id/spr_place_type"
                android:text="@string/str_btn_find" />

    <fragment
                android:id="@+id/map"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/spr_place_type"
                class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>


1.)  dialog_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center_horizontal" >
   
    <TextView
        android:id="@+id/tv_vicinity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        android:maxLines="2" />
   
    <ViewFlipper
        android:id="@+id/flipper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >       
    </ViewFlipper>
   
    <TextView
        android:id="@+id/tv_photos_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
</LinearLayout>

Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


public class MainActivity extends FragmentActivity{
   
    // GoogleMap
    GoogleMap mGoogleMap;
   
    // Spinner in which the location types are stored
    Spinner mSprPlaceType;
   
    // A button to find the near by places
    Button mBtnFind=null;
   
    // Stores near by places
    Place[] mPlaces = null;
   
    // A String array containing place types sent to Google Place service
    String[] mPlaceType=null;
   
    // A String array containing place types displayed to user
    String[] mPlaceTypeName=null;
   
    // The location at which user touches the Google Map
    LatLng mLocation=null;
   
    // Links marker id and place object
    HashMap<String, Place> mHMReference = new HashMap<String, Place>();
   
    // Specifies the drawMarker() to draw the marker with default color
    private static final float UNDEFINED_COLOR = -1;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {       
       
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);       
       
        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);
       
        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
       
        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
       
        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
       
        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);   
       
        // Getting reference to Find Button
        mBtnFind = ( Button ) findViewById(R.id.btn_find);       
       
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
       
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

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

        }else { // Google Play Services are available
           
            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                   
            // Getting Google Map
            mGoogleMap = fragment.getMap();
                   
            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);   
           
            // Handling screen rotation
            if(savedInstanceState !=null) {
               
                // Removes all the existing links from marker id to place object
                mHMReference.clear();
               
                //If near by places are already saved
                if(savedInstanceState.containsKey("places")){
                   
                    // Retrieving the array of place objects
                    mPlaces = (Place[]) savedInstanceState.getParcelableArray("places");
                   
                    // Traversing through each near by place object
                    for(int i=0;i<mPlaces.length;i++){
                       
                        // Getting latitude and longitude of the i-th place
                        LatLng point = new LatLng(Double.parseDouble(mPlaces[i].mLat),
                                                  Double.parseDouble(mPlaces[i].mLng));
                       
                        // Drawing the marker corresponding to the i-th place
                        Marker m = drawMarker(point,UNDEFINED_COLOR);
                       
                        // Linkng i-th place and its marker id
                        mHMReference.put(m.getId(), mPlaces[i]);
                    }
                   
                }
               
                // If a touched location is already saved
                if(savedInstanceState.containsKey("location")){
                   
                    // Retrieving the touched location and setting in member variable
                    mLocation = (LatLng) savedInstanceState.getParcelable("location");
                   
                    // Drawing a marker at the touched location
                    drawMarker(mLocation, BitmapDescriptorFactory.HUE_GREEN);                                       
                }
            }      
           
                       
            // Setting click event lister for the find button
            mBtnFind.setOnClickListener(new OnClickListener() {
               
                @Override
                public void onClick(View v) {                   
                   
                    int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                    String type = mPlaceType[selectedPosition];
                   
                    mGoogleMap.clear();
                   
                   
                    if(mLocation==null){
                        Toast.makeText(getBaseContext(), "Please mark a location", Toast.LENGTH_SHORT).show();
                        return;                       
                    }
                   
                    drawMarker(mLocation, BitmapDescriptorFactory.HUE_GREEN);                                       
                   
                    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                    sb.append("location="+mLocation.latitude+","+mLocation.longitude);
                    sb.append("&radius=5000");
                    sb.append("&types="+type);
                    sb.append("&sensor=true");
                    sb.append("&key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE");
                   
                   
                    // Creating a new non-ui thread task to download Google place json data
                    PlacesTask placesTask = new PlacesTask();                                   
                   
                    // Invokes the "doInBackground()" method of the class PlaceTask
                    placesTask.execute(sb.toString());
                }
            });
           
            // Map Click listener
            mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
               
                @Override
                public void onMapClick(LatLng point) {
                   
                    // Clears all the existing markers
                    mGoogleMap.clear();
                   
                    // Setting the touched location in member variable
                    mLocation = point;
                   
                    // Drawing a marker at the touched location
                    drawMarker(mLocation,BitmapDescriptorFactory.HUE_GREEN);
                   
                }
            });           
           
            // Marker click listener
            mGoogleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
               
                @Override
                public boolean onMarkerClick(Marker marker) {
                   
                    // If touched at User input location
                    if(!mHMReference.containsKey(marker.getId()))
                        return false;           
                   
                    // Getting place object corresponding to the currently clicked Marker
                    Place place = mHMReference.get(marker.getId());
                   
                    // Creating an instance of DisplayMetrics
                    DisplayMetrics dm = new DisplayMetrics();
                   
                    // Getting the screen display metrics
                    getWindowManager().getDefaultDisplay().getMetrics(dm);
                   
                    // Creating a dialog fragment to display the photo
                    PlaceDialogFragment dialogFragment = new PlaceDialogFragment(place,dm);                  

                    // Getting a reference to Fragment Manager
                    FragmentManager fm = getSupportFragmentManager();
                   
                    // Starting Fragment Transaction
                    FragmentTransaction ft = fm.beginTransaction();
                   
                    // Adding the dialog fragment to the transaction
                    ft.add(dialogFragment, "TAG");
                   
                    // Committing the fragment transaction
                    ft.commit();
                   
                    return false;
                }
            });       
        }           
    }   
   
    /**
     * A callback function, executed on screen rotation
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
       
        // Saving all the near by places objects
        if(mPlaces!=null)
            outState.putParcelableArray("places", mPlaces);
       
        // Saving the touched location
        if(mLocation!=null)
            outState.putParcelable("location", mLocation);
       
        super.onSaveInstanceState(outState);
    }
   
   
    /** A method to download json data from argument url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);               
               

                // Creating an http connection to communicate with url
                urlConnection = (HttpURLConnection) url.openConnection();               

                // Connecting to url
                urlConnection.connect();               

                // Reading data from url
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }

                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }
        return data;
    }        

   
    /** A class, to download Google Places */
    private class PlacesTask extends AsyncTask<String, Integer, String>{

        String data = null;
       
        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try{
                Log.d("URL:",url[0]);
                data = downloadUrl(url[0]);
            }catch(Exception e){
                 Log.d("Background Task",e.toString());
            }
            return data;
        }
       
        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result){           
            ParserTask parserTask = new ParserTask();           
           
            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of ParserTask
            parserTask.execute(result);
        }
       
    }
   
    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, Place[]>{

        JSONObject jObject;
       
        // Invoked by execute() method of this object
        @Override
        protected Place[] doInBackground(String... jsonData) {   
           
           
            Place[] places = null;
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();
       
            try{
                jObject = new JSONObject(jsonData[0]);               
                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);
               
            }catch(Exception e){
                    Log.d("Exception",e.toString());
            }
            return places;
        }
       
        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(Place[] places){               
           
            mPlaces = places;
           
            for(int i=0;i< places.length  ;i++){
           
                Place place = places[i];   
   
                // Getting latitude of the place
                double lat = Double.parseDouble(place.mLat);               
               
                // Getting longitude of the place
                double lng = Double.parseDouble(place.mLng);
               
                LatLng latLng = new LatLng(lat, lng);           
               
                Marker m = drawMarker(latLng,UNDEFINED_COLOR);          
               
                // Adding place reference to HashMap with marker id as HashMap key
                // to get its reference in infowindow click event listener
                mHMReference.put(m.getId(), place);
               
            }
        }   
       
    }
       
    /**
     * Drawing marker at latLng with color
     */
    private Marker drawMarker(LatLng latLng,float color){
        // Creating a marker
        MarkerOptions markerOptions = new MarkerOptions();               
       
        // Setting the position for the marker
        markerOptions.position(latLng);
       
        if(color != UNDEFINED_COLOR)
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(color));
       
        // Placing a marker on the touched position
        Marker m = mGoogleMap.addMarker(markerOptions);
       
        return m;    

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



1.)  Attribution.java


package com.mapv2.demo;

import android.os.Parcel;
import android.os.Parcelable;

public class Attribution implements Parcelable{
   
    // Attribution of the photo
    String mHtmlAttribution="";

    @Override
    public int describeContents() {       
        return 0;
    }

    /** Writing Attribution object data to Parcel */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mHtmlAttribution);       
    }
   
    public Attribution(){
       
    }
   
    /**  Initializing Attribution object from Parcel object */
    private Attribution(Parcel in){
        this.mHtmlAttribution = in.readString();
    }
   
    /** Generates an instance of Attribution class from Parcel */
    public static final Parcelable.Creator<Attribution> CREATOR = new Parcelable.Creator<Attribution>() {

        @Override
        public Attribution createFromParcel(Parcel source) {           
            return new Attribution(source);
        }

        @Override
        public Attribution[] newArray(int size) {
            // TODO Auto-generated method stub
            return null;
        }
    };   
}




2.)  Photo.java
package com.mapv2.demo;

import android.os.Parcel;
import android.os.Parcelable;

public class Photo implements Parcelable{
   
    // Width of the Photo
    int mWidth=0;
   
    // Height of the Photo
    int mHeight=0;   
   
    // Reference of the photo to be used in Google Web Services
    String mPhotoReference="";
   
    // Attributions of the photo
    // Attribution is a Parcelable class
    Attribution[] mAttributions={};
   
    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }
   
    /** Writing Photo object data to Parcel */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mWidth);
        dest.writeInt(mHeight);
        dest.writeString(mPhotoReference);
        dest.writeParcelableArray(mAttributions, 0);
       
    }
   
    public Photo(){       
    }
   
    /**  Initializing Photo object from Parcel object */
    private Photo(Parcel in){
        this.mWidth = in.readInt();
        this.mHeight = in.readInt();
        this.mPhotoReference = in.readString();
        this.mAttributions = (Attribution[])in.readParcelableArray(Attribution.class.getClassLoader());
    }
   
    /** Generates an instance of Place class from Parcel */
    public static final Parcelable.Creator<Photo> CREATOR = new Parcelable.Creator<Photo>() {
        @Override
        public Photo createFromParcel(Parcel source) {           
            return new Photo(source);
        }

        @Override
        public Photo[] newArray(int size) {
            // TODO Auto-generated method stub
            return null;
        }
    };   
}



3.)  Place.java
package com.mapv2.demo;

import android.os.Parcel;
import android.os.Parcelable;

public class Place implements Parcelable{
    // Latitude of the place
    String mLat="";
   
    // Longitude of the place
    String mLng="";
   
    // Place Name
    String mPlaceName="";
   
    // Vicinity of the place
    String mVicinity="";
   
    // Photos of the place
    // Photo is a Parcelable class
    Photo[] mPhotos={};
   
    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }       
   
    /** Writing Place object data to Parcel */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mLat);
        dest.writeString(mLng);
        dest.writeString(mPlaceName);
        dest.writeString(mVicinity);
        dest.writeParcelableArray(mPhotos, 0);   
    }
   
    public Place(){       
    }
   
    /** Initializing Place object from Parcel object */
    private Place(Parcel in){
        this.mLat = in.readString();
        this.mLng = in.readString();
        this.mPlaceName = in.readString();
        this.mVicinity = in.readString();
        this.mPhotos = (Photo[])in.readParcelableArray(Photo.class.getClassLoader());               
    }
   
   
    /** Generates an instance of Place class from Parcel */
    public static final Parcelable.Creator<Place> CREATOR = new Parcelable.Creator<Place>(){
        @Override
        public Place createFromParcel(Parcel source) {           
            return new Place(source);
        }

        @Override
        public Place[] newArray(int size) {
            // TODO Auto-generated method stub
            return null;
        }       
    };
}


4.)  PlaceDialogFragment.java
package com.mapv2.demo;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

// Defining DialogFragment class to show the place details with photo
public class PlaceDialogFragment extends DialogFragment{
       
    TextView mTVPhotosCount = null;
    TextView mTVVicinity = null;
    ViewFlipper mFlipper = null;
    Place mPlace = null;
    DisplayMetrics mMetrics = null;
       
    public PlaceDialogFragment(){
        super();
    }
       
    public PlaceDialogFragment(Place place, DisplayMetrics dm){
        super();               
        this.mPlace = place;
        this.mMetrics  = dm;
    }
       
    @Override
    public void onCreate(Bundle savedInstanceState) {           
           
        // For retaining the fragment on screen rotation
        setRetainInstance(true);       
        super.onCreate(savedInstanceState);
    }   
       
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.dialog_layout, null);
           
        // Getting reference to ViewFlipper
        mFlipper = (ViewFlipper) v.findViewById(R.id.flipper);
       
        // Getting reference to TextView to display photo count
        mTVPhotosCount = (TextView) v.findViewById(R.id.tv_photos_count);
       
        // Getting reference to TextView to display place vicinity
        mTVVicinity = (TextView) v.findViewById(R.id.tv_vicinity);
           
           
        if(mPlace!=null){
               
            // Setting the title for the Dialog Fragment
            getDialog().setTitle(mPlace.mPlaceName);
       
            // Array of references of the photos
            Photo[] photos = mPlace.mPhotos;
           
            // Setting Photos count
            mTVPhotosCount.setText("Photos available : " + photos.length);
           
            // Setting the vicinity of the place
            mTVVicinity.setText(mPlace.mVicinity);           
                   
            // Creating an array of ImageDownloadTask to download photos
            ImageDownloadTask[] imageDownloadTask = new ImageDownloadTask[photos.length];
               
            int width = (int)(mMetrics.widthPixels*3)/4;   
            int height = (int)(mMetrics.heightPixels*1)/2;
               
            String url = "https://maps.googleapis.com/maps/api/place/photo?";
            String key = "key=YOUR_BROWSER_KEY";
            String sensor = "sensor=true";
            String maxWidth="maxwidth=" + width;
            String maxHeight = "maxheight=" + height;
            url = url + "&" + key + "&" + sensor + "&" + maxWidth + "&" + maxHeight;                       
               
            // Traversing through all the photoreferences
            for(int i=0;i<photos.length;i++){
                // Creating a task to download i-th photo
                imageDownloadTask[i] = new ImageDownloadTask();
               
                String photoReference = "photoreference="+photos[i].mPhotoReference;
               
                // URL for downloading the photo from Google Services
                url = url + "&" + photoReference;
               
                // Downloading i-th photo from the above url
                imageDownloadTask[i].execute(url);
            }    
        }
        return v;
    }
       
    @Override
    public void onDestroyView() {
        if (getDialog() != null && getRetainInstance())
            getDialog().setDismissMessage(null);
        super.onDestroyView();
    }
   
   
    private Bitmap downloadImage(String strUrl) throws IOException{
        Bitmap bitmap=null;
        InputStream iStream = null;
        try{
            URL url = new URL(strUrl);
           
            /** Creating an http connection to communcate with url */
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            /** Connecting to url */
            urlConnection.connect();

            /** Reading data from url */
            iStream = urlConnection.getInputStream();

            /** Creating a bitmap from the stream returned from the url */
            bitmap = BitmapFactory.decodeStream(iStream);

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
        }
        return bitmap;
    }
   
    private class ImageDownloadTask extends AsyncTask<String, Integer, Bitmap>{
        Bitmap bitmap = null;
        @Override
        protected Bitmap doInBackground(String... url) {
            try{
                // Starting image download
                bitmap = downloadImage(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            // Creating an instance of ImageView to display the downloaded image              
            ImageView iView = new ImageView(getActivity().getBaseContext());           

            // Setting the downloaded image in ImageView
            iView.setImageBitmap(result);
           
            // Adding the ImageView to ViewFlipper
            mFlipper.addView(iView);           

            // Showing download completion message
            Toast.makeText(getActivity().getBaseContext(), "Image downloaded successfully", Toast.LENGTH_SHORT).show();
        }
    }
}


5.)  PlaceJSONParser.java
package com.mapv2.demo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class PlaceJSONParser {
   
    /** Receives a JSONObject and returns a list */
    public Place[] parse(JSONObject jObject){       
       
        JSONArray jPlaces = null;
        try {           
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaces(jPlaces);
    }
   
   
    private Place[] getPlaces(JSONArray jPlaces){
        int placesCount = jPlaces.length();       
        Place[] places = new Place[placesCount];   

        /** Taking each place, parses and adds to list object */
        for(int i=0; i<placesCount;i++){
            try {
                /** Call getPlace with place JSON object to parse the place */
                places[i] = getPlace((JSONObject)jPlaces.get(i));               
               

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
       
        return places;
    }
   
    /** Parsing the Place JSON object */
    private Place getPlace(JSONObject jPlace){

        Place place = new Place();
       
               
       
        try {
            // Extracting Place name, if available
            if(!jPlace.isNull("name")){               
                place.mPlaceName = jPlace.getString("name");
            }
           
            // Extracting Place Vicinity, if available
            if(!jPlace.isNull("vicinity")){
                place.mVicinity = jPlace.getString("vicinity");
            }   
           
            if(!jPlace.isNull("photos")){
                JSONArray photos = jPlace.getJSONArray("photos");
                place.mPhotos = new Photo[photos.length()];
                for(int i=0;i<photos.length();i++){
                    place.mPhotos[i] = new Photo();
                    place.mPhotos[i].mWidth = ((JSONObject)photos.get(i)).getInt("width");
                    place.mPhotos[i].mHeight = ((JSONObject)photos.get(i)).getInt("height");
                    place.mPhotos[i].mPhotoReference = ((JSONObject)photos.get(i)).getString("photo_reference");
                    JSONArray attributions = ((JSONObject)photos.get(i)).getJSONArray("html_attributions");
                    place.mPhotos[i].mAttributions = new Attribution[attributions.length()];
                    for(int j=0;j<attributions.length();j++){
                        place.mPhotos[i].mAttributions[j] = new Attribution();
                        place.mPhotos[i].mAttributions[j].mHtmlAttribution = attributions.getString(j);
                    }                   
                }
            }
           
            place.mLat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
            place.mLng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");                       
           
           
           
        } catch (JSONException e) {           
            e.printStackTrace();
            Log.d("EXCEPTION", e.toString());
        }       
        return place;
    }
}

Step 6 :- Run Code.



Step 7 :- Download Code :-  https://dl.dropboxusercontent.com/u/109954727/Map/map29.zip