This tutorial is very helpful if you are building any application which deals with user locations. In this article i explained how to integrate Google Places and Maps in your android application.

Download Code

About Google Places

Google Places API is a service provided by Google which returns information about your nearest places by considering the latitude, longitude and radius of area. You can add or remove a place from their places service too. Everything is done just by sending an HTTP request with required parameters. Check their official documentation for more information.

Prerequisite

In this tutorial i used lot of my previous tutorials. If you are new to any of the following concepts, i recommend you learn that particular topic just to make this tutorial easy.
> Android Working with Google Maps
> Android GPS, Location Manager Tutorial
> Android Detect Internet Connection Status

Obtaining Google API Key

In order to make requests to Google Places API you need to provide your API key along with the other parameters. You can get your API key by going to Google Places APIs console. The same key can be used for all other google services. Check the following video to know how to get a api key.

New Project / Downloading required libraries

Open your Eclipse IDE and create a new android project and fill all the required details. Also make sure that you have the updated ADT (Android Development Tool) and Eclipse to latest version.

1. Create a new project File ? New ? Android Application Project.

For this project i downloaded lot of external jar files and added to my project. These libraries are used to parse the Google API response.

Go to http://code.google.com/p/google-api-java-client/wiki/Setup and download google-api-client-android2. Extract the files and place them (Not every file) inside libs folder in your project. The following are required files you need to paste in your project.

1. google-api-client-1.10.3-beta.jar
2. google-api-client-android2-1.10.3-beta.jar (only for SDK >= 2.1)
3. google-oauth-client-1.10.3-beta.jar
4. google-http-client-1.10.3-beta.jar
5. google-http-client-android2-1.10.3-beta.jar (only for SDK >= 2.1)
6. google-http-client-android3-1.10.3-beta.jar (only for SDK >= 3.0)
7. gson-2.1.jar
8. guava-11.0.1.jar
9. jackson-core-asl-1.9.4.jar
10. jsr305-1.3.9.jar
11. protobuf-java-2.2.0.jar

3. As this application needs internet connection, we need to detect whether user has working internet connection or not. For this i am creating a new class called ConnectionDetector.java and pasted the following code.

Refer Android Detect Internet Connection Status to know more about using this class.

package com.androidhive.googleplacesandmaps;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
 
public class ConnectionDetector {
 
    private Context _context;
 
    public ConnectionDetector(Context context){
        this._context = context;
    }
 
    /**
     * Checking for all possible internet providers
     * **/
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
    }
}

4. Just to show messages in Alert Dialog i am creating a reusable alert class so that you don’t have to write the alert code in all the activities. Create a new class and name it as AlertDialogManager.java

package com.androidhive.googleplacesandmaps;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AlertDialogManager {
	/**
	 * Function to display simple Alert Dialog
	 * @param context - application context
	 * @param title - alert dialog title
	 * @param message - alert message
	 * @param status - success/failure (used to set icon)
	 * 				 - pass null if you don't want icon
	 * */
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		if(status != null)
			// Setting alert dialog icon
			alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}
}

5. In this tutorial as everything is based on user’s current location, we need to get user’s current location using GPS. Create a new class called GPSTracker.java and paste the following code. To know more about this class usage follow this Android GPS, Location Manager Tutorial

package com.androidhive.googleplacesandmaps;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

	private final Context mContext;

	// flag for GPS status
	boolean isGPSEnabled = false;

	// flag for network status
	boolean isNetworkEnabled = false;

	// flag for GPS status
	boolean canGetLocation = false;

	Location location = null; // location
	double latitude; // latitude
	double longitude; // longitude

	// The minimum distance to change Updates in meters
	private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

	// The minimum time between updates in milliseconds
	private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

	// Declaring a Location Manager
	protected LocationManager locationManager;

	public GPSTracker(Context context) {
		this.mContext = context;
		getLocation();
	}

	public Location getLocation() {
		try {
			locationManager = (LocationManager) mContext
					.getSystemService(LOCATION_SERVICE);

			// getting GPS status
			isGPSEnabled = locationManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);

			// getting network status
			isNetworkEnabled = locationManager
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

			if (!isGPSEnabled && !isNetworkEnabled) {
				// no network provider is enabled
			} else {
				this.canGetLocation = true;
				if (isNetworkEnabled) {
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER,
							MIN_TIME_BW_UPDATES,
							MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
					Log.d("Network", "Network Enabled");
					if (locationManager != null) {
						location = locationManager
								.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
						if (location != null) {
							latitude = location.getLatitude();
							longitude = location.getLongitude();
						}
					}
				}
				// if GPS Enabled get lat/long using GPS Services
				if (isGPSEnabled) {
					if (location == null) {
						locationManager.requestLocationUpdates(
								LocationManager.GPS_PROVIDER,
								MIN_TIME_BW_UPDATES,
								MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
						Log.d("GPS", "GPS Enabled");
						if (locationManager != null) {
							location = locationManager
									.getLastKnownLocation(LocationManager.GPS_PROVIDER);
							if (location != null) {
								latitude = location.getLatitude();
								longitude = location.getLongitude();
							}
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return location;
	}

	/**
	 * Stop using GPS listener Calling this function will stop using GPS in your
	 * app
	 * */
	public void stopUsingGPS() {
		if (locationManager != null) {
			locationManager.removeUpdates(GPSTracker.this);
		}
	}

	/**
	 * Function to get latitude
	 * */
	public double getLatitude() {
		if (location != null) {
			latitude = location.getLatitude();
		}

		// return latitude
		return latitude;
	}

	/**
	 * Function to get longitude
	 * */
	public double getLongitude() {
		if (location != null) {
			longitude = location.getLongitude();
		}

		// return longitude
		return longitude;
	}

	/**
	 * Function to check GPS/wifi enabled
	 * 
	 * @return boolean
	 * */
	public boolean canGetLocation() {
		return this.canGetLocation;
	}

	/**
	 * Function to show settings alert dialog On pressing Settings button will
	 * lauch Settings Options
	 * */
	public void showSettingsAlert() {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

		// Setting Dialog Title
		alertDialog.setTitle("GPS is settings");

		// Setting Dialog Message
		alertDialog
				.setMessage("GPS is not enabled. Do you want to go to settings menu?");

		// On pressing Settings button
		alertDialog.setPositiveButton("Settings",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(
								Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						mContext.startActivity(intent);
					}
				});

		// on pressing cancel button
		alertDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});

		// Showing Alert Message
		alertDialog.show();
	}

	@Override
	public void onLocationChanged(Location location) {
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}

6. While parsing google places api response, it is better to make every place as an object to make it reusable component. So create the following classes.

Place.java – Single place as object

package com.androidhive.googleplacesandmaps;

import java.io.Serializable;

import com.google.api.client.util.Key;

/** Implement this class from "Serializable"
* So that you can pass this class Object to another using Intents
* Otherwise you can't pass to another actitivy
* */
public class Place implements Serializable {

	@Key
	public String id;
	
	@Key
	public String name;
	
	@Key
	public String reference;
	
	@Key
	public String icon;
	
	@Key
	public String vicinity;
	
	@Key
	public Geometry geometry;
	
	@Key
	public String formatted_address;
	
	@Key
	public String formatted_phone_number;

	@Override
	public String toString() {
		return name + " - " + id + " - " + reference;
	}
	
	public static class Geometry implements Serializable
	{
		@Key
		public Location location;
	}
	
	public static class Location implements Serializable
	{
		@Key
		public double lat;
		
		@Key
		public double lng;
	}
	
}

PlacesList.java – List of places

package com.androidhive.googleplacesandmaps;

import java.io.Serializable;
import java.util.List;

import com.google.api.client.util.Key;

/** Implement this class from "Serializable"
* So that you can pass this class Object to another using Intents
* Otherwise you can't pass to another actitivy
* */
public class PlacesList implements Serializable {

	@Key
	public String status;

	@Key
	public List<Place> results;

}

PlaceDetails.java – Single place full details as object

package com.androidhive.googleplacesandmaps;

import java.io.Serializable;

import com.google.api.client.util.Key;

/** Implement this class from "Serializable"
* So that you can pass this class Object to another using Intents
* Otherwise you can't pass to another actitivy
* */
public class PlaceDetails implements Serializable {

	@Key
	public String status;
	
	@Key
	public Place result;

	@Override
	public String toString() {
		if (result!=null) {
			return result.toString();
		}
		return super.toString();
	}
}

Getting Google Places

7. The actual part of getting google places is sarted now. Create a new class called GooglePlaces.java and write the following code. This class has function which are used to make request to Google Places API. While searching places your can search for particular type of places like cafe, restaurants etc,. Check list of supported types of places.

In the following class we have two functions

// This function is used to search your nearest places
public PlacesList search(double latitude, double longitude, double radius, 
         String types)...
// This function is used to get full details of a particular place
public PlaceDetails getPlaceDetails(String reference)...

Final code

package com.androidhive.googleplacesandmaps;

import org.apache.http.client.HttpResponseException;

import android.util.Log;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpParser;
import com.google.api.client.json.jackson.JacksonFactory;

@SuppressWarnings("deprecation")
public class GooglePlaces {

	/** Global instance of the HTTP transport. */
	private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

	// Google API Key
	private static final String API_KEY = "AIzaSyCRLa4LQZWNQBcjCYcIVYA45i9i8zfClqc";

	// Google Places serach url's
	private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
	private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
	private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";

	private double _latitude;
	private double _longitude;
	private double _radius;

	/**
	 * Searching places
	 * @param latitude - latitude of place
	 * @params longitude - longitude of place
	 * @param radius - radius of searchable area
	 * @param types - type of place to search
	 * @return list of places
	 * */
	public PlacesList search(double latitude, double longitude, double radius, String types)
			throws Exception {

		this._latitude = latitude;
		this._longitude = longitude;
		this._radius = radius;

		try {

			HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
			HttpRequest request = httpRequestFactory
					.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
			request.getUrl().put("key", API_KEY);
			request.getUrl().put("location", _latitude + "," + _longitude);
			request.getUrl().put("radius", _radius); // in meters
			request.getUrl().put("sensor", "false");
			if(types != null)
				request.getUrl().put("types", types);

			PlacesList list = request.execute().parseAs(PlacesList.class);
			// Check log cat for places response status
			Log.d("Places Status", "" + list.status);
			return list;

		} catch (HttpResponseException e) {
			Log.e("Error:", e.getMessage());
			return null;
		}

	}

	/**
	 * Searching single place full details
	 * @param refrence - reference id of place
	 * 				   - which you will get in search api request
	 * */
	public PlaceDetails getPlaceDetails(String reference) throws Exception {
		try {

			HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
			HttpRequest request = httpRequestFactory
					.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
			request.getUrl().put("key", API_KEY);
			request.getUrl().put("reference", reference);
			request.getUrl().put("sensor", "false");

			PlaceDetails place = request.execute().parseAs(PlaceDetails.class);
			
			return place;

		} catch (HttpResponseException e) {
			Log.e("Error in Perform Details", e.getMessage());
			throw e;
		}
	}

	/**
	 * Creating http request Factory
	 * */
	public static HttpRequestFactory createRequestFactory(
			final HttpTransport transport) {
		return transport.createRequestFactory(new HttpRequestInitializer() {
			public void initialize(HttpRequest request) {
				GoogleHeaders headers = new GoogleHeaders();
				headers.setApplicationName("AndroidHive-Places-Test");
				request.setHeaders(headers);
				JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
				request.addParser(parser);
			}
		});
	}

}

Showing Places in ListView

8. Create two xml files under layout folder required for creating a listview. In the following i am creating a listview and a button above the listview. Another file is for list item. Name the two files as activity_main.xml and list_item.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"> 
    
    <!-- Show on Map button -->
    <Button android:id="@+id/btn_show_map"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Show Places on Map"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dip"/>
    
    <!--  List view -->
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_show_map"/>
    
    
 
</RelativeLayout>

list_item.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" >
    
    <TextView android:id="@+id/reference"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <TextView android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textStyle="bold"
        android:textSize="16dip"/>
</LinearLayout>

9. Open your main acitivity (my main activity name is MainActivity.java) and add following required variables.

public class MainActivity extends Activity {

	// flag for Internet connection status
	Boolean isInternetPresent = false;

	// Connection detector class
	ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	// Google Places
	GooglePlaces googlePlaces;

	// Places List
	PlacesList nearPlaces;

	// GPS Location
	GPSTracker gps;

	// Button
	Button btnShowOnMap;

	// Progress dialog
	ProgressDialog pDialog;
	
	// Places Listview
	ListView lv;
	
	// ListItems data
	ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
	
	
	// KEY Strings
	public static String KEY_REFERENCE = "reference"; // id of the place
	public static String KEY_NAME = "name"; // name of the place
	public static String KEY_VICINITY = "vicinity"; // Place area name

	@Override
	public void onCreate(Bundle savedInstanceState) {

In the following code
> First i am checking if user has internet connection or not. If not an alert is shown to user asking to connect to internet

> Second i am checking if user’s current location can be retrieved by GPS Location Manger. If not an alert is shown asking user to turn on GPS or Wifi.

> Third if user has both internet and GPS turned on an Async task is called to get Google places using new LoadPlaces().execute()

> In LoadPlaces() method once getting places is done all the data is attached in a ListView.

> Above the listview a button is placed which launches another activity to show all places on map.

package com.androidhive.googleplacesandmaps;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class MainActivity extends Activity {

	// flag for Internet connection status
	Boolean isInternetPresent = false;

	// Connection detector class
	ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	// Google Places
	GooglePlaces googlePlaces;

	// Places List
	PlacesList nearPlaces;

	// GPS Location
	GPSTracker gps;

	// Button
	Button btnShowOnMap;

	// Progress dialog
	ProgressDialog pDialog;
	
	// Places Listview
	ListView lv;
	
	// ListItems data
	ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
	
	
	// KEY Strings
	public static String KEY_REFERENCE = "reference"; // id of the place
	public static String KEY_NAME = "name"; // name of the place
	public static String KEY_VICINITY = "vicinity"; // Place area name

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		isInternetPresent = cd.isConnectingToInternet();
		if (!isInternetPresent) {
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}

		// creating GPS Class object
		gps = new GPSTracker(this);

		// check if GPS location can get
		if (gps.canGetLocation()) {
			Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
		} else {
			// Can't get user's current location
			alert.showAlertDialog(MainActivity.this, "GPS Status",
					"Couldn't get location information. Please enable GPS",
					false);
			// stop executing code by return
			return;
		}

		// Getting listview
		lv = (ListView) findViewById(R.id.list);
		
		// button show on map
		btnShowOnMap = (Button) findViewById(R.id.btn_show_map);

		// calling background Async task to load Google Places
		// After getting places from Google all the data is shown in listview
		new LoadPlaces().execute();

		/** Button click event for shown on map */
		btnShowOnMap.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(),
						PlacesMapActivity.class);
				// Sending user current geo location
				i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
				i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
				
				// passing near places to map activity
				i.putExtra("near_places", nearPlaces);
				// staring activity
				startActivity(i);
			}
		});
		
		
		/**
		 * ListItem click event
		 * On selecting a listitem SinglePlaceActivity is launched
		 * */
		lv.setOnItemClickListener(new OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	// getting values from selected ListItem
                String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
                
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SinglePlaceActivity.class);
                
                // Sending place refrence id to single place activity
                // place refrence id used to get "Place full details"
                in.putExtra(KEY_REFERENCE, reference);
                startActivity(in);
            }
        });
	}

	/**
	 * Background Async Task to Load Google places
	 * */
	class LoadPlaces extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			// creating Places class object
			googlePlaces = new GooglePlaces();
			
			try {
				// Separeate your place types by PIPE symbol "|"
				// If you want all types places make it as null
				// Check list of types supported by google
				// 
				String types = "cafe|restaurant"; // Listing places only cafes, restaurants
				
				// Radius in meters - increase this value if you don't find any places
				double radius = 1000; // 1000 meters 
				
				// get nearest places
				nearPlaces = googlePlaces.search(gps.getLatitude(),
						gps.getLongitude(), radius, types);
				

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * and show the data in UI
		 * Always use runOnUiThread(new Runnable()) to update UI from background
		 * thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed Places into LISTVIEW
					 * */
					// Get json response status
					String status = nearPlaces.status;
					
					// Check for all possible status
					if(status.equals("OK")){
						// Successfully got places details
						if (nearPlaces.results != null) {
							// loop through each place
							for (Place p : nearPlaces.results) {
								HashMap<String, String> map = new HashMap<String, String>();
								
								// Place reference won't display in listview - it will be hidden
								// Place reference is used to get "place full details"
								map.put(KEY_REFERENCE, p.reference);
								
								// Place name
								map.put(KEY_NAME, p.name);
								
								
								// adding HashMap to ArrayList
								placesListItems.add(map);
							}
							// list adapter
							ListAdapter adapter = new SimpleAdapter(MainActivity.this, placesListItems,
					                R.layout.list_item,
					                new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
					                        R.id.reference, R.id.name });
							
							// Adding data into listview
							lv.setAdapter(adapter);
						}
					}
					else if(status.equals("ZERO_RESULTS")){
						// Zero results found
						alert.showAlertDialog(MainActivity.this, "Near Places",
								"Sorry no places found. Try to change the types of places",
								false);
					}
					else if(status.equals("UNKNOWN_ERROR"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry unknown error occured.",
								false);
					}
					else if(status.equals("OVER_QUERY_LIMIT"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry query limit to google places is reached",
								false);
					}
					else if(status.equals("REQUEST_DENIED"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry error occured. Request is denied",
								false);
					}
					else if(status.equals("INVALID_REQUEST"))
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry error occured. Invalid Request",
								false);
					}
					else
					{
						alert.showAlertDialog(MainActivity.this, "Places Error",
								"Sorry error occured.",
								false);
					}
				}
			});

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	

}
android detecting internet connection
Android google places api

Getting single place full details

11. If you see the api json response from google, each place has a unique reference id which is used to get place complete details.

In your project create a new Activity class and name it as SinglePlaceActivity.java and respected layout file and name it as single_place.xml

single_place.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" 
    android:padding="10dip">
    
    <!-- Name Label -->
    <TextView
        android:text="Name:"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:layout_marginBottom="5dip"
        android:textStyle="bold"/>
    
    <!--  Name Value -->
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <!-- Address Label -->
    <TextView
        android:text="Address:"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginBottom="5dip"
        android:textStyle="bold"/>
    
    <!--  Address Value -->
    <TextView
        android:id="@+id/address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <!-- Phone Number Label -->
    <TextView
        android:id="@+id/phone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"/>
    
    
    <!-- Location Value -->
    <TextView
        android:id="@+id/location"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginBottom="5dip"/>


</LinearLayout>

And below is the code for SinglePlaceActivity.java class. In the following code

> First the place reference id is received from MainActivity.java activity

> Second using the place reference id a background Async thread LoadSinglePlaceDetails() is called to get full details of a place

package com.androidhive.googleplacesandmaps;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;

public class SinglePlaceActivity extends Activity {
	// flag for Internet connection status
	Boolean isInternetPresent = false;

	// Connection detector class
	ConnectionDetector cd;
	
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();

	// Google Places
	GooglePlaces googlePlaces;
	
	// Place Details
	PlaceDetails placeDetails;
	
	// Progress dialog
	ProgressDialog pDialog;
	
	// KEY Strings
	public static String KEY_REFERENCE = "reference"; // id of the place

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.single_place);
		
		Intent i = getIntent();
		
		// Place referece id
		String reference = i.getStringExtra(KEY_REFERENCE);
		
		// Calling a Async Background thread
		new LoadSinglePlaceDetails().execute(reference);
	}
	
	
	/**
	 * Background Async Task to Load Google places
	 * */
	class LoadSinglePlaceDetails extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(SinglePlaceActivity.this);
			pDialog.setMessage("Loading profile ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Profile JSON
		 * */
		protected String doInBackground(String... args) {
			String reference = args[0];
			
			// creating Places class object
			googlePlaces = new GooglePlaces();

			// Check if used is connected to Internet
			try {
				placeDetails = googlePlaces.getPlaceDetails(reference);

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed Places into LISTVIEW
					 * */
					if(placeDetails != null){
						String status = placeDetails.status;
						
						// check place deatils status
						// Check for all possible status
						if(status.equals("OK")){
							if (placeDetails.result != null) {
								String name = placeDetails.result.name;
								String address = placeDetails.result.formatted_address;
								String phone = placeDetails.result.formatted_phone_number;
								String latitude = Double.toString(placeDetails.result.geometry.location.lat);
								String longitude = Double.toString(placeDetails.result.geometry.location.lng);
								
								Log.d("Place ", name + address + phone + latitude + longitude);
								
								// Displaying all the details in the view
								// single_place.xml
								TextView lbl_name = (TextView) findViewById(R.id.name);
								TextView lbl_address = (TextView) findViewById(R.id.address);
								TextView lbl_phone = (TextView) findViewById(R.id.phone);
								TextView lbl_location = (TextView) findViewById(R.id.location);
								
								// Check for null data from google
								// Sometimes place details might missing
								name = name == null ? "Not present" : name; // if name is null display as "Not present"
								address = address == null ? "Not present" : address;
								phone = phone == null ? "Not present" : phone;
								latitude = latitude == null ? "Not present" : latitude;
								longitude = longitude == null ? "Not present" : longitude;
								
								lbl_name.setText(name);
								lbl_address.setText(address);
								lbl_phone.setText(Html.fromHtml("<b>Phone:</b> " + phone));
								lbl_location.setText(Html.fromHtml("<b>Latitude:</b> " + latitude + ", <b>Longitude:</b> " + longitude));
							}
						}
						else if(status.equals("ZERO_RESULTS")){
							alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
									"Sorry no place found.",
									false);
						}
						else if(status.equals("UNKNOWN_ERROR"))
						{
							alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
									"Sorry unknown error occured.",
									false);
						}
						else if(status.equals("OVER_QUERY_LIMIT"))
						{
							alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
									"Sorry query limit to google places is reached",
									false);
						}
						else if(status.equals("REQUEST_DENIED"))
						{
							alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
									"Sorry error occured. Request is denied",
									false);
						}
						else if(status.equals("INVALID_REQUEST"))
						{
							alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
									"Sorry error occured. Invalid Request",
									false);
						}
						else
						{
							alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
									"Sorry error occured.",
									false);
						}
					}else{
						alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
								"Sorry error occured.",
								false);
					}
					
					
				}
			});

		}

	}

}
android google place full details

Showing all the places on the Map

If you haven’t worked with maps yet, go through Android Working with Google Maps to get an idea about implementing google maps in your android application.

In our MainActivity you can find a button called Show On Map to show all the places on the map. This the code to call map activity by passing all the places information to PlacesMapActivity.java

This code is implemented in MainActivity.java class

/** Button click event for shown on map */
		btnShowOnMap.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(),
						PlacesMapActivity.class);
				// Sending user current geo location
				i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
				i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
				
				// passing near places to map activity
				i.putExtra("near_places", nearPlaces);
				// staring activity
				startActivity(i);
			}
		});

12. Create a new class called AddItemizedOverlay.java which is helper class for map activity used to display markers, geopoints on a map.

package com.androidhive.googleplacesandmaps;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

/**
 * Class used to place marker or any overlay items on Map
 * */
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
 
       private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
 
       private Context context;
 
       public AddItemizedOverlay(Drawable defaultMarker) {
            super(boundCenterBottom(defaultMarker));
       }
 
       public AddItemizedOverlay(Drawable defaultMarker, Context context) {
            this(defaultMarker);
            this.context = context;
       }
       
       @Override
       public boolean onTouchEvent(MotionEvent event, MapView mapView)
       {   
 
           if (event.getAction() == 1) {
               GeoPoint geopoint = mapView.getProjection().fromPixels(
                   (int) event.getX(),
                   (int) event.getY());
               // latitude
               double lat = geopoint.getLatitudeE6() / 1E6;
               // longitude
               double lon = geopoint.getLongitudeE6() / 1E6;
               //Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
           }
           return false;
       } 
 
       @Override
       protected OverlayItem createItem(int i) {
          return mapOverlays.get(i);
       }
 
       @Override
       public int size() {
          return mapOverlays.size();
       }
 
       @Override
       protected boolean onTap(int index) {
         OverlayItem item = mapOverlays.get(index);
         AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
         dialog.setTitle(item.getTitle());
         dialog.setMessage(item.getSnippet());
         dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int which) {
 			}
 		});
         dialog.show();
         return true;
       }
 
       public void addOverlay(OverlayItem overlay) {
          mapOverlays.add(overlay);
       }
       
       public void populateNow(){
    	   this.populate();
       }
 
    }

13. Create a new class called PlacesMapActivity.java which is the activity to display all the places on the map.

In the following code
> User current location is showed on map in a red marker.

> Remaining all the places are shown in blue markers.

package com.androidhive.googleplacesandmaps;

import java.util.List;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class PlacesMapActivity extends MapActivity {
	// Nearest places
	PlacesList nearPlaces;

	// Map view
	MapView mapView;

	// Map overlay items
	List<Overlay> mapOverlays;

	AddItemizedOverlay itemizedOverlay;

	GeoPoint geoPoint;
	// Map controllers
	MapController mc;
	
	double latitude;
	double longitude;
	OverlayItem overlayitem;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_places);

		// Getting intent data
		Intent i = getIntent();
		
		// Users current geo location
		String user_latitude = i.getStringExtra("user_latitude");
		String user_longitude = i.getStringExtra("user_longitude");
		
		// Nearplaces list
		nearPlaces = (PlacesList) i.getSerializableExtra("near_places");

		mapView = (MapView) findViewById(R.id.mapView);
		mapView.setBuiltInZoomControls(true);

		mapOverlays = mapView.getOverlays();
		
		// Geopoint to place on map
		geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
				(int) (Double.parseDouble(user_longitude) * 1E6));
		
		// Drawable marker icon
		Drawable drawable_user = this.getResources()
				.getDrawable(R.drawable.mark_red);
		
		itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
		
		// Map overlay item
		overlayitem = new OverlayItem(geoPoint, "Your Location",
				"That is you!");

		itemizedOverlay.addOverlay(overlayitem);
		
		mapOverlays.add(itemizedOverlay);
		itemizedOverlay.populateNow();
		
		// Drawable marker icon
		Drawable drawable = this.getResources()
				.getDrawable(R.drawable.mark_blue);
		
		itemizedOverlay = new AddItemizedOverlay(drawable, this);

		mc = mapView.getController();

		// These values are used to get map boundary area
		// The area where you can see all the markers on screen
		int minLat = Integer.MAX_VALUE;
		int minLong = Integer.MAX_VALUE;
		int maxLat = Integer.MIN_VALUE;
		int maxLong = Integer.MIN_VALUE;

		// check for null in case it is null
		if (nearPlaces.results != null) {
			// loop through all the places
			for (Place place : nearPlaces.results) {
				latitude = place.geometry.location.lat; // latitude
				longitude = place.geometry.location.lng; // longitude
				
				// Geopoint to place on map
				geoPoint = new GeoPoint((int) (latitude * 1E6),
						(int) (longitude * 1E6));
				
				// Map overlay item
				overlayitem = new OverlayItem(geoPoint, place.name,
						place.vicinity);

				itemizedOverlay.addOverlay(overlayitem);
				
				
				// calculating map boundary area
				minLat  = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
			    minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
			    maxLat  = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
			    maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
			}
			mapOverlays.add(itemizedOverlay);
			
			// showing all overlay items
			itemizedOverlay.populateNow();
		}
		
		// Adjusting the zoom level so that you can see all the markers on map
		mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
		
		// Showing the center of the map
		mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
		mapView.postInvalidate();

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

}
android showing google places on map
android google places on map popup
This is image for thumbnail purpose.
android working with google places and maps

Finally if you downloaded the code provided in this tutorial, don’t forget to replace the Google API key with your own key.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Hello your tutorial is awesome this is what i need in my project
    Thank You Very much

    By the way

    How can i Change this from MapView to MapFragment
    I’m having problem in mapview cuz’ it only display gridlines and markers

    THANK YOU IN ADVANCE

  • suresh

    hi ravi,

    code is working very fine 2 weaks before. now am getting always places error. request denaied….

  • Theo

    Why force closes? I changed API key at Googleplaces.java. What else I am missing? I downloaded files import project and it didn’t show any app on my emulator so I created everything as above and copied, pasted.

  • rajendra

    how to retrieve distance for nearby

  • ericntd

    Hi Ravi,

    Thanks for your awesome tutorial.

    I’ve followed the steps and used the sample codes.

    Everything works out nicely except that when I click on “Show PLaces on Map”, the map does not show and there is an exception “android_maps_conflict_avoidance.com.google.googlenav.map.basetilerequest.readresponsedata”

    I wonder if this have to with compatability of the codes with Google Maps Android API v2, ADT v21 or API level 15 that I’m targeting.

    Would appreciate if you could update your tutorial or shed some light on this issue.

    Thank you,
    Eric

  • Rajesh MBM

    hey this code is working fine. but the problem , it is not tracing my current location. every time it is showing my location latitude is: 37.422005 and longitude is: -122.084095. how to make this code to detect my location rather than US county as default location. I tried with changing values manually from emulator, but still no reslut. any help would be appreciated…

  • Zayyad

    Appreciate your tuts sir. But i’m faced with the problem of displaying only the grid lines of the google map. can u plz suggest possible solutions? tnx

  • Ravi Teja

    You are the man…. Your are Awesome brooo…. Thank you very much for the tutorial…. @Ravi Teja

  • Nani

    Hi, can I know how to save my location(lat and longitude) in text file using outputstream so that i can review my location’s history.

  • sarath

    Its Google map API V2. Now what ?

  • Gafsiano

    I got the solution myself. Problem was with the Googleapis-1.15.0.jar import that was the culprit for which the compiler wasn’t able to change data due to access restriction inside. And it was creating issues in GoogleHeaders.java.

    It sets the userAgent variable via setApplicationName method that required access for the compiler. However, this is now modified as below.

    Following is the new code for GoogleHeaders. Hope it helps for all such users.

    HttpHeaders headers = new HttpHeaders();
    headers.setUserAgent(“Searching Places..”);
    request.setHeaders(headers);

    and for the parser you can use this code
    JsonObjectParser parser = new JsonObjectParser(new JacksonFactory());
    request.setParser(parser);

    Remove GoogleHeaders usage in full and it would run smoothly as a knife.

    Cheers!

  • Hi I need your help with the tutorial you made using google places api android, I’m running and sending the coordinates according to what you taught in the video, if I put more coordinated another says she was not found.

  • Joe

    Google Place is only showing 3 cafes and restaurants which are within 1km, while the actual google maps app from google is showing there are more than 10 within 1km which is correct.

  • Naina

    The latitude and longitude are always “0” whenever i run my app 🙁 it shows no places found because of this problem…please help me to get over this..its urgent..
    i am executing the code on my android phone

  • Si War

    hi

    i follow the tutorials, but when i run the application i’ve got this message (Unfortunately, Google Places and Maps has stopped.) whit OK button

    can any one got the same error plz help,

    Thanks

    • madhu

      I have the same error. could u solve it? pls help me

    • jawad

      hi i just have run the code and got the same error(Unfortunately, Google Places and Maps has stopped.) .. could u help to resolve it ..

  • Ben Sap

    PLEASE CAN U ADD DIRECTIONS TO THE TUTORIALS………..

  • Valentin

    I just cant get rid of this error
    Could not find class ‘com.google.api.client.http.javanet.NetHttpTransport’, referenced from method com.androidhive.googleplacesandmaps.GooglePlaces.
    and the app crashes.
    Im using the latest google-api-java-client-1.15.0-rc. Added all the jars to the build path and added also the sources to the jars. Ive tried also some older versions but I get the same error.

    Would appreciate any help.

    Thanx

    • madhu

      i have the same error, could u solve? pls help me

  • Ahmad Zu Abu Lebda

    Hi
    all application works fine but i have problem in maps . mpas does not appear but the location appears in white scenes.

    THANKS

  • madhu

    PLS help me, i recieve “could not find class com.google.api.client.http.javanet.NetHttpTransport” error at runtime. PLS help me,

  • Ben Sap

    please can any one show me how to add directions on the map places……

  • Ro

    How can I resolve : “The import com.google.api.client.googleapis.GoogleHeaders cannot be resolved” ?

  • SkunkWorks KU

    Hey Christie.Did you get a solution am stuck with a similar problem

  • SkunkWorks KU

    Did you get the solution? I am stuck with a similar problem

    • Algeriassic

      Go to Google APIs Console and activate “Places API”

  • SkunkWorks KU

    Got a solution? Stuck with the same problem here

  • Mohamed Emad

    i got this error

    06-13 17:36:50.604: E/dalvikvm(466): Could not find class ‘com.google.api.client.http.javanet.NetHttpTransport’, referenced from method com.androidhive.googleplacesandmaps.GooglePlaces.

    • raptors

      on Project > properties > Android , First I remove Google API then I clean the project , in this step you get some errors on some java class ,Second step go to the same address an Check the box of Google API and after clean project and it works, enjoy !!!

  • Mohamed Emad

    Nobody answer me about that error

    06-13 17:36:50.604: E/dalvikvm(466): Could not find class ‘com.google.api.client.http.javanet.NetHttpTransport’, referenced from method com.androidhive.googleplacesandmaps.GooglePlaces.

    • Amiyo

      Add jar file under libs

  • kais

    how can i add new places to this project i mean some personal places help please

    • Raline

      yes..the same problem here..?

  • smaran

    Does this code work for google v2?

  • Asim

    Do you know anyway to show the places that I have predefined in “My places” maps. Thanks

  • Amey B

    Ravi, this code used to work previously, but now suddenly it has stopped working. can you please tell us why?

  • jayakrishnan

    my emulator is not supported,which configuration is best one for this application thank you in advance plzz help me

  • Venu

    when i click on show places on map button
    am getting FATAL EXCEPTION: main

    at com.androidhive.googleplacesandmaps.MainActivity$1.onClick(MainActivity.java:110)

    at android.view.View.performClick(View.java:3528)

    : at android.view.View$PerformClick.run(View.java:14235)

    at android.os.Handler.handleCallback(Handler.java:605)

    at android.os.Handler.dispatchMessage(Handler.java:92)

    at android.app.ActivityThread.main(ActivityThread.java:4424)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:511)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)

    : at dalvik.system.NativeStart.main(Native Method)

    Caused by: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation

    at dalvik.system.DexFile.defineClass(Native Method)

    : at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:195)

    at dalvik.system.DexPathList.findClass(DexPathList.java:315)

    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:58)

    at javalang.ClassLoader.loadClass(ClassLoader.java:501)

    : at java.lang.ClassLoader.loadClass(ClassLoader.java:461)

    … 12 more

    how to reslove this problem

  • Madhuri

    A fabulous tutorial… d only problem i am facing is the map is not being displayed….rest everything is functional.. even d locators are visible but on a grid layout not on a map…can u plz help me out..??

  • Ajay C Resta

    Could not find class ‘org.codehaus.jackson.JsonFactory’, referenced from method com.google.api.client.json.jackson.JacksonFactory.

  • Herahadi An

    hello i downloaded your project and try to run it but its give me these following error “GooglePlacesAndMaps] Installation error: INSTALL_FAILED_MISSING_SHARED_LIBRARY”

    i look at the libs folder, and all needed library is already there.. so what should i do??

  • Solutino

    Hi sir, can you please tell me how to check this application in a device having lower version(2.3.3) OS?

  • Amit

    Hi Ravi,
    such a nice tutorial, very clear and useful as well, you have shown places around you in a good manner 🙂

    In my one of the commercial app i am using this tutorial, now i need to change this code with Maps API V2, Please update ….many developers are using this awesome tutorial…

    God Bless You

  • srikanth gutti

    here near by means how far from user.

  • Periklis P.

    hello, can i use this tutorial with the other one with user registration and login in mysql database
    i want users to locate their own lang and long and see other users to google map

    is that possible?
    thanks in advanced

  • DarkM

    Hello,
    Can you modify this example to work with google map v2 using mapfragment.

  • Rupesh

    Hey suppose I want to show direction in between current location and location where user touches.How could it be done?

    How to get response from https://maps.googleapis.com/maps/api/directions/json?

    Please give me the sample code.

    Thanks..

  • K

    you need to use Key for browser apps ,not the one for Android

  • Anoop

    Google map not showing but all others are working fine . As your video tutorial i generated the key but map not showing …

  • Alessandro

    Hi Sir, I’ve a problem, the import

    import com.google.api.client.googleapis.GoogleHeaders;
    import com.google.api.client.http.json.JsonHttpParser;

    don’t works.
    Eclipse say to me: The import com.google.api.client.http.json.JsonHttpParser cannot be resolved

    Probably it is a problem of the version of the imported jar but I can’t solve it

  • Anmar

    Hi guys, im having problems with displaying the maps. My location + nearby places show up but the map does not.

    I have followed the youtube instruction to create my own API key and pasted it into

    GooglePlaces.java at -> private static final String API_KEY = “”; // place your API key here

    I also generated a Android key in google api console like so:

    Key for Android apps (with certificates)API key:

    XXX;com.androidhive.googleplacesandmaps

    And pasted this key into mapl_places.xml at android:apiKey=”XXX”

    But it still seems not to be working.

    Does anybody know why?

    Appreciate the help

    • Davy

      Hey did u find a solution to that ? Pls share.

    • Babu Kaliyamoorthy

      I am struggling by the same problem what u faced before.Please suggest me.

  • Jayakrishnan

    my map shows only grid with markers how to solve this. i am following this tutorial

  • karan vir

    There is a bug in the PlacesMapActivity.java file.
    The Android is throwing me this error getOverlays cannot be resolved or is not a field.
    Can you please help me in trouble shooting this ?
    Thanks!

  • swetha

    Hi i need to load the map that shows the address details using markers stored in mysql database ….When i select ok to the address pop up in map, it should direct to listview containing address details that are taken from mysql database…Can u pls suggest me to do my project..Also im new to android ,pls reply me……

  • rajan

    i m trying to implement search restaurent it shows create class HttpTransport

  • Guest

    Dude its displaying location but not the map…is it because of deprecation?

  • Nirav Kamani

    https://code.google.com/p/google-api-java-client/wiki/Setup these link is given by you at the starting of this tutorial to download the jar file. There is only google-api-java-client-1.16.0-rc.zip so am i right should i download this? or anything else?

  • Harsukh

    u get any solution?

  • kartick

    hi ravi, thanks for great tutorial for google maps..i want to use this example using google maps version 2..can u publish this example using version 2 google maps.again thanks for great tutorial.

  • Udhaya Banu

    very good tutorial. but for me its showing all places when i leave the type as null why it is not showing my nearest places & when i give anything in the type its throwing me error.I have put my api key in the google api key do i need to change anywhere please guide me

  • E. Pavez

    I’m gettin problems with the class GooglePlaces.

    A lot of methods says that are undefined for the type HttpTransport like getUrl(), createRequestFactory(), setHeaders() and addParser().

    Thanks!

    • Icaro

      Remove all libraries that you was added and add again.

  • ruaa

    i am getting the error “sorry no places found”

  • MrT

    i can not run this app..can you help me try it. the problem is: ” no compatible targes were found . although i choose AVD targes : Android 2.2 (Google ips…)

  • esra’a

    Hi,i am getting problem in google places class “The application google places has stopped unexpectedly” ,please can help me?

  • Amin

    Well done buddy,
    when I fetch places, the name of some of them contains unusual characters like square. I think they are not in english language but I don’t know how to convert them.

  • Sur

    Hi Ravi,

    Your tutorial has always been very helpful for me. I am working on google maps and i need show/focus nearest airport and draw a path to the airport from the list how can i do that? Any idea!!

  • mudit srivastava

    hello sir,
    how can we print the distance value in listview and join the places by line on map.

  • Gorgon Medusa

    Why can’t I download? Redirecting me to firewall/firewall/php?

    • Yeah, problem in server. Its fixed now.

      • amiyo

        hello ravi sir , I insert my own key in to that code but when i run this ,the simulator shows message that “unfortunately application has stopped” .
        Would you help me why this app not run . waiting for your reply .

        • meghna

          hello ,
          i have also same problem plz reply me if u get answer. i am using level 21 which jar file i have to use

      • meghna

        Hello sir,

        plzzzz help me. My application is unfortunately stop, I am adding android key in java code and browser key without url in xml file. if url key is add which url add.
        plz send me mail at meghashine22@gmail.com

  • Guest

    i just want to search some places about “hospital”,then i changed String types from “cafe|restaurant” to ” hospitals” or “bệnh viện” but it not work..can u help me use the key about this..tks i’m using longitude:106.694589 , latitude:10.804837

  • Shay

    Hi. Good work you have here. I need your help. How can I add my own list of restaurants manually in your application above? My list of restaurants based on latitude and longitude. Really need an answer for this. Thank you in advance for any help you can provide.

  • Esteban

    Hi!, I need to ask you something, do you know how to work with photos in that API?. I went to the documentation but I don’t understand how it is done.

    Thanks!

  • Kaviraj

    Hello … i am having problem with the import of these:

    import com.google.android.maps.GeoPoint;

    import com.google.android.maps.MapActivity;

    import com.google.android.maps.MapController;

    import com.google.android.maps.MapView;

    import com.google.android.maps.Overlay;

    import com.google.android.maps.OverlayItem;

    Am try to insert the map in an existing project , i tried to import the google play services lib but error still remains … any suggestion why . Please help.

    • srinaveen

      Download android-google-maps-api11.jar from net and insert it into libs folder

  • Kaviraj

    Hello , When you set the target as Google Inc API ,the errors are gone, when you are try to export your application to a APK , it say can’t find project . Any idea ?

  • rangaprakash

    hi i am new for API and maps i need a tutorial for android maps from basics onwards with step by step procedure can anybody plz send a mail prakash.boggarapu@gmail.com

  • amiyo

    hello ravi sir , I insert my own key in to that code but when i run this ,the simulator shows message that “unfortunately application has stopped” .
    Would you help me why this app not run . waiting for your reply .

    • Pragadees

      Add jar file.
      right click projects->properties->select java build path->choose libraries->add external jars then
      choose order and export and choose all the jars and the libraries

  • Waleed A. Afifi

    Hello,
    Thanks for this its really help me.
    But i have one question if i want to get the place location from sql database on my website how to do that.
    If you can help me please send me an email waleed-afifi@windowslive.com

  • rajat jain

    i downloaded the project but didn’t know where to insert the key

  • Kaustv Ghosh

    Can you please update the above code for Google API V2.It will be very helpful then.

    • Francesco Messineo

      you managed to fix with version 2?

  • ghufran

    i m getting error “sorry query limit to google places is reached”

  • ghufran

    and also “REQUEST_DENIED”

    • Nishtha

      Were you able to resolve this problem of request denied?

      • When creating the API key in the Google console, leaving the URLs field blank made mine work

        • yeonju

          please answer detailed…

          • Cát Khang

            The Rising Page . Did you show map ?

  • new2android

    hi i downloaded the tutorial code and changed the api key …….when i am executing ……i am getting output as sorry request is denied………

  • Antara

    hello,is there anyway to select the
    destination location from listview and locate selected location on maps
    and show the route from my current location to user selected destination
    location??

  • Sushin PS

    hello,
    it is working fine for projects which doesnot uses appcombat_v7 library. Why it is not working while doing with appcombat_v7. The imports are not working.

  • Sridhar

    Heloo, I get the all the places include with markers, but the map does not display here. only i viewed the checked background page with the markers. kindly help me on this.

  • Thouseef

    Really very good and useful post…. Just got wat i need… Super

  • Hamza

    GooglePlacesAndMaps] Installation error: INSTALL_FAILED_MISSING_SHARED_LIBRARY help me please

  • Bhavika

    It is showing error in AddItemizedOverlay.java and PlacesMapActivity.java file. It doesnt allow me to import the following packages

    import com.google.android.maps.GeoPoint;

    import com.google.android.maps.ItemizedOverlay;

    import com.google.android.maps.MapView;

    import com.google.android.maps.OverlayItem;

    I have added all jar files. Still it is showing errors. Its urgent. Please Help.. Thanks

    • Bhavika

      I have solved this errors by adding this(android-google-maps-api11.jar) JAR file. Now it is showing all nearest places. But when I click on show Places on map button, It is throing exception AndroidRuntime(1066): java.lang.NoClassDefFoundError: com/androidhive/googleplacesandmaps/PlacesMapActivity

      AndroidRuntime(1066): at com.androidhive.googleplacesandmaps.MainActivity$1.onClick(MainActivity.java:110)

      What I need to do for this?? Please Help…

      • Did you solve this error?

        • dina

          i have this problem

      • ky

        how do you add api 11 jar file in?

      • Sandip Borad

        Great.. bhavika i have solve this error..

        • Babu Kaliyamoorthy

          can u please tell the suggestion to solve this error.

  • Bhavika

    Download this JAR file(android-google-maps-api11.jar) and put it in your libs folder.

  • Rafael Ruiz Tabares

    Great tutorial again! But this method is obsolete. So people who got problem with libraries and class’ method….only it’s necessary to import google maps and adding markers for the same result (there is a fabulous tutorial in this site about this matter)

  • Cát Khang

    Why not show map in PlacesMap Activity(only icons) . Please help me . Thanks all .

  • Yaz

    Why not show map in PlacesMap Activity(only icons) . Please help me . Thanks all .

    • wael

      plz if u solved ur problem tell me how
      thnx 🙂

  • Arun Prasath

    i had an error in SinglePlaceActivity.java and it said to import the .JAR file and after importing it , i got errors in ADDITEMIZEDOVERLAY.java and PLACESMAPACTIVITY.java .
    please help me to resolve this soon.

  • dina

    when iam run the application have an error request is denied ? any help please

    • wael

      check the api key (of the google places)

  • Vineel Sadineni

    Its working fine and the places are visible,but the map is not shown!!please help?

  • dandy argan

    For anyone who can’t manage to SHOW the maps and only see MARKER, its because this tutorial still using google maps API v1. This tutorial still run well if u change the map code with API v2. U can see this tutorial how to do it http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/ . If u still confuse u can see this explanation either http://mobisys.in/blog/2013/04/google-maps-android-api-v2-different-operations/ . This way u can manage to change map version to maps API v2 🙂

    • guest

      Thanks. It would be great if u can share your code 🙂

  • dhruvang joshi

    Its working fine,but we need only city list within 100km from current location. So how to get that. Can u help me????

  • Ying Min

    Can someone help me with how to display map? Why it is not displaying?

    • henry

      hi did you manage to get it displayed?

  • Kwstas Na

    Can anyone send him an e-mail to update, if he can of course, the code for google maps api v3?
    thnx a lot 🙂

  • Abhishek

    i searched with cafe|restaurant|bar, i got all these in radius of 3kms,
    i searched with hospital, i got all these in radius of 3kms,
    got banks also, atms also,
    I searched with shoppingmall but in this case i haven’t got the desirable result and same is the case with cinemas

  • Naveen kant Mishra

    Hi sir need your help on a point google pai returns max 20 data for a search. How to get more than 20 data if we need in some case…by using pagination or else…

  • yogesh6297 .

    heyy ravi and everyone Hii ,can you please tell me how to send string data from onPostExecute method of AsyncTask to another activity and second question how to get reviews from google places.Thanx in Advance

  • great site …. i need assistance with plotting users of my app on a map with the app

  • Davood Hanifi

    Hi can every body send me converted code from google map v1 to google map v2 to me?

  • Usman Asif

    can i done this without api

  • great site….very gud info…

  • Hitesh Kumar

    Hey…did anyone get an expection like android.intent.action.PACKAGE_ADDED,android.intent.action.PACKAGE_REMOVED…etc….may i know the reason why…unable to comprehend the reason…….because of that exception,places request is not getting fulfilled!!!

  • zakhar

    When i click on show places on map, i get unfortunately Google place and maps has stopped.

    what’s the problem ?

    here we see the cat log after clicking :

    10-25 11:23:19.173: E/AndroidRuntime(798): FATAL EXCEPTION: main

    10-25 11:23:19.173: E/AndroidRuntime(798): java.lang.NoClassDefFoundError: com/androidhive/googleplacesandmaps/PlacesMapActivity

    10-25 11:23:19.173: E/AndroidRuntime(798): at com.androidhive.googleplacesandmaps.MainActivity$1.onClick(MainActivity.java:110)

  • Harpreet

    I don’t want to copy this I want to create it by my own.I mean how did you get to know what jar file will be needed & what not .How did you start this project.how come you know what to use & what not.

  • Kumar

    Mapview is not loading it displays only the grids but the markers are displaying the map’s view can’t be viewed.Can you help me

    • Check your API key is correct.

      • Allen Zhang

        The codes is based on google map v1. That is the problem, isn’t it?

  • Kathy Kefas

    thank you so much, everything is working well. But i don’t want my nearby places to be searched for automatically, i want to give a list of coordinates that will be compared to my location and the nearby places should be gotten from that, please how do i include that, please i need help

  • Rohini

    thanks a lot.. dis code helped me a lot

  • baskar

    Thank u ravi for posting a useful code. based on ur code i developed an app and posted in google play store with some modifications and currently working in google map v2 to show map in my application. Thanks again and please continue to give some valuable codes like this. my play store app link: https://play.google.com/store/apps/details?id=com.baskar.cafe&hl=en waiting for the user comments to add more functionality. Thank u

    • Allen Zhang

      Why I couldn’t open your app link? Could you update that again please? If you could send it to my e-mail I would be really appreciated. I am fresh in this field thank you.

  • baskar

    if (nearPlaces.results != null) {
    // loop through all the places
    for (Place place : nearPlaces.results) {
    latitude = place.geometry.location.lat; // latitude
    longitude = place.geometry.location.lng; // longitude

    When i try to get the latitude and longitude, it shows me the current location, can anyone help me with this.

    • baskar

      i found the answer, that was my mistake the coding works good.

  • baskar

    Want to implement Google mapv2 in this project, Plz follow my app to get an idea. https://play.google.com/store/apps/details?id=com.baskar.cafe&hl=en . Thank u

  • Its throwing following error when i try run this project copy with PRODUARD Configured.

    I have Edited

    -keep class com.google.** {*;}
    -keep interface com.google.** { *;}
    -dontwarn com.google.**

    ________________________________

    LOGCAT Errors:
    _____________

    `12-02 15:21:53.920: E/AndroidRuntime(30503): FATAL EXCEPTION: main

    12-02 15:21:53.920: E/AndroidRuntime(30503): Process: com.androidhive.googleplacesandmaps, PID: 30503

    12-02 15:21:53.920: E/AndroidRuntime(30503): java.lang.NullPointerException

    12-02 15:21:53.920: E/AndroidRuntime(30503): at com.androidhive.googleplacesandmaps.l.run(Unknown Source)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at android.app.Activity.runOnUiThread(Activity.java:4713)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at com.androidhive.googleplacesandmaps.k.a(Unknown Source)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at com.androidhive.googleplacesandmaps.k.onPostExecute(Unknown Source)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at android.os.AsyncTask.finish(AsyncTask.java:632)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at android.os.AsyncTask.access$600(AsyncTask.java:177)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at android.os.Handler.dispatchMessage(Handler.java:102)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at android.os.Looper.loop(Looper.java:136)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at android.app.ActivityThread.main(ActivityThread.java:5001)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at java.lang.reflect.Method.invokeNative(Native Method)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at java.lang.reflect.Method.invoke(Method.java:515)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

    12-02 15:21:53.920: E/AndroidRuntime(30503): at dalvik.system.NativeStart.main(Native Method)`

    Help please..

  • Changhong yang

    When i click on show places on map, i get unfortunately Google place and maps has stopped.???

    12-10 01:39:24.176: E/AndroidRuntime(10007): FATAL EXCEPTION: main

    12-10 01:39:24.176: E/AndroidRuntime(10007): java.lang.NoClassDefFoundError: com/androidhive/googleplacesandmaps/PlacesMapActivity

    12-10 01:39:24.176: E/AndroidRuntime(10007): at com.androidhive.googleplacesandmaps.MainActivity$1.onClick(MainActivity.java:110)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at android.view.View.performClick(View.java:4232)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at android.view.View$PerformClick.run(View.java:17298)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at android.os.Handler.handleCallback(Handler.java:615)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at android.os.Handler.dispatchMessage(Handler.java:92)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at android.os.Looper.loop(Looper.java:137)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at android.app.ActivityThread.main(ActivityThread.java:4921)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at java.lang.reflect.Method.invokeNative(Native Method)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at java.lang.reflect.Method.invoke(Method.java:511)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at dalvik.system.NativeStart.main(Native Method)

    12-10 01:39:24.176: E/AndroidRuntime(10007): Caused by: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation

    12-10 01:39:24.176: E/AndroidRuntime(10007): at dalvik.system.DexFile.defineClass(Native Method)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:211)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at dalvik.system.DexPathList.findClass(DexPathList.java:315)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:58)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)

    12-10 01:39:24.176: E/AndroidRuntime(10007): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)

    12-10 01:39:24.176: E/AndroidRuntime(10007): … 12 more

    • Changhong yang

      Help please me ..

  • Juliano Vince de Campos

    Congratulations!!!! Congratulations!!!
    My name is Juliano Vince.
    your tutorials are perfect.
    Thank you so much!

  • John David

    At the moment I can display all the nearest restaurants to me using Google API (https://developers.google.com/places/documentation/supported_types).

    My problem is I want to filter only Pizza Hut’s nearest to me. How can I do that? Is it possible to do using Google places API or if there are any other option?

    When I Google saying “nearest pizza hut to me”, it shows 3 nearest pizza hut locations on Google map – I want to do something similar on my android mobile app.

  • arwa

    i want to show path from source to destination on google map using google map api v2 , how would i do this plzzz tell me .

  • manju kumari

    everything is working fine in the code but map is not showing in the background …….i have also replaced api key in map_places.xml with my own api key for google maps v2 but still its not showing

    • Mohammad

      Even i have the same problem Manju Kumari, Ravi can you help us

      • May be you are implementing the old maps. Try using the new maps
        http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/

        • Mohammad

          Hi I have a problem with thehttp://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/,that is Registration gets expired in 7 days, again i need to reinstall the app when this problem occurs. Can u please tell me how to overcome it from the above code.

  • Eriq

    It’s a pitty it’s not working. The download code seems to be outdated. Would be nice if this could be updated to API v2.

  • Mardoqueu

    Could you make a tutorial about Web Server + Google Maps v2 + SQLite? specific about marks, I mean if I want to put more marks on the App instead of to put on the code and upload again into the device I just send using the web server to App and it saves the new marks on the APP using SQLite. Do you know how to do that?

  • RE DA

    could you make tutorial about how you can know location of someone please

  • Alagu Sundar

    can i open and run this project in android studio. please help me. its urjent

  • neha

    Failed to find mapViewStyle ……… uSE THEME COMBO BOX FOR THIS LAYOUT

  • sajid

    hi ravi!! i have implemented this app but when i click on show on map button the mapview is just showing markers wat to do man i am stuck please help me out

    • Hi Sajid,

      Try using the latest version of Google maps
      http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/

      • sajid

        do i have to get the two api keys to run my appliction i have used both maps api and places api , whats the difference between android api key and dekstop api key your answers will be helpful !!!

      • meghna

        Hai Ravi. When I try to run this code, it shows Request is Denied. No
        Maps and lists of cafes are shown. Please help me and give a solution
        for this problem. Thank you.

  • Max Vignesh

    hey..
    i am using android studio..
    where did i copy the jar files …into my project …
    import com.google.api.. gives me error ..
    i tried a lot of times..
    please someone help me please… guys

    • Eclipse is much better than AS.

      • Max Vignesh

        Yeah i am agree with u Mr.Shifar Shift but moving to new things will save our Precious time .. so that only i am Using..

        Do u have ANSWER for my Error..
        If u Know Means Please Help Me…

  • Max Vignesh

    Guys I have an another Problem…

    com.google.android.maps. is not working …brings me error.. in android studio

    please help me to solve this ….

  • Max Vignesh

    map_places layout codings is not found here …

    please help to solve this map_places layout codings..

  • anbu

    i have some problem sorry error occred. Request is denied. give me solution please

    • sanjay thakur

      plz open your place service on from console

  • Shashwat Agnihotri

    wat if we need to do it for a particular place such as searching for a list of hospitals in ur location

  • Nisha

    Hai Ravi. When I try to run this code, it shows Request is Denied. No Maps and lists of cafes are shown. Please help me and give a solution for this problem. Thank you.

  • omar

    please anyone can help to change to mapv2 and apply it to this project pleaseee ! some codes are different from mapv1 to mapv2 .

  • anonymous

    please anyone can help to change to mapv2 and apply it to this project pleaseee ! some codes are different from mapv1 to mapv2

  • Shahin fathima

    Why it is showing only the restuarants details alone ?

  • irfan

    i hv changed the API KEY with my own key…..
    but when i click on button SHOW PLACES ON MAP suddenly application is closed and dialogue box appear which shows…(unfortunately google places and maps has stopped)….
    wt shld i do now? plz help me its urgent…..

    • irfan

      i hv chngd the api key with my own key in googleplaces.java file also but now its showing
      “sorry error occured request is denied”….
      plz rply

  • anonymous

    I have been tryibg to change it to mapv2 and apply it to this project! But many Errors Are coming!! Could you pls post the changed code in map V2

  • Danish Amjad

    I want to get a photos from JSON how can i get? anyone knows?

  • Zaky B.

    Hi your tutorial looks very helpfull and i tried implementing it. However it didn’t work out 100% as i hoped. I added a question on stackoverflow if you could check it on this link please : http://stackoverflow.com/questions/29943158/status-variable-returns-nullpointerexception-android

    Thank you,

    • Zaky B.

      Nobody an idea? Really stuck with this at the moment

  • Hassan Ibrahim

    heloooo… thats a great work…
    Sir I’ve a problem… you are using Android V1 which in now obsolete… Google is not giving the key for API V1, So we have to move on to v2 and v3… Can you plz help me in converting PlacesMapActivity.Java in V2…
    My email adress is: malik.131@hotmail.com

  • Aw Oo

    hey ravi, any tutorial for google direction API?

  • Devendra Singh

    Your code has been outdated. the MapActivity is deprecated now.

  • mohit

    java.lang.NoClassDefFoundError: com/androidhive/googleplacesandmaps/PlacesMapActivity

  • M0TRIX

    can u export the project.thats much esaier… i have problem with R file.i does not recognize it.

    look at the PlacesMapActivity class. lines : setContentView(R.layout.map_places);
    mapView = (MapView) findViewById(R.id.mapView);

  • Shweta Chauhan

    in this tutorial you use two api key- in GooglePlaces.java file and map_places.xml i generate my api key but at which place i put my api key and what is difference between that 2 key

    • abc android

      there are two key
      1=browser key
      2=android key
      1 key u have u define in xml file and
      2 key mention in java code

  • Shweta Chauhan

    I try this tutorial but i saw only nearest place when i click on showmap it show only blue and red marker not map plz give solution

  • Govind

    app:dexDebug error.. please help

  • suyash

    sir, where is the GeoPoint ,Itemizedoverlay, mapview, overlayitem classes i can found thgis clases in your code

  • स्वप्नील भदे

    Hi I got Status message REQUEST_DENIED Error. I replaced API Key. How to solve this problem?

  • abc android

    hey ravi thanks for sharig your code.but aprat of it i do search somthing like cng ,petrol ,police station nothing are srearch .plz tell me how to do it or need something else .hope u consider my querey

  • amit

    Hello Ravi,

    when i dont change the android api key it works fine except it does not show the map..but puts the markers. Now when i use my keys it gives me request denied error.

    What i have done is that I have generated a android key and a browser key. The android key i am putting in the map_place.xml and the browser key in the activity file. I HAVE ENABLED THE API IN THE GOOGLE CONSOLE. I still get the request denied error. Any help on this.

    • OldMonker

      I finally got this resolved. Just remade the keys and now it works. Second scene is that he map shows only grid but not the map itself. i found out that there is something to do with version of 1 and 2. We should be using fragment instead of calling com.maps. I not got it though. Any other ways to get this done.

      • sasha

        hi i have the same problem too did you solve it?
        could u help me with it?
        my email:
        saeed.f436@gmail.com
        thanks

      • sasha

        how you done it?
        can you share your code here please !!

      • Piyush Gupta

        plz send me procedur my aap is forcely down

    • sasha

      hi i have the same problem too did you solve it?
      could u help me with it?
      my email:
      saeed.f436@gmail.com

      • RAMAN KRISHNA

        actually google places api key is only obtained from paid google services.

  • OldMonker

    I have worked with this code for long now and realized that there are a lot of changes. The overlay and lot other methods are deprecated. Using maps v1 is not an option any more. So the logic is all fine but the code needs to be rewritten. When i am done will post the git here.

    • Ernesto E. Valenzuela

      Hi OldMonker, hope you’re ok, do you have ready the methods that you mentioned are deprecated? Please share them with me, I need them to complete a section of my school project. Thanks!

    • Mouadh Saidani

      can you share your code here please !!

    • ramadan byouk

      hello sir did manage to do it …. if you did can plss explain how did u do it

    • NikzArkz

      can you share your code please ???

  • Sharath Hegde

    Ravi Sir,
    Is there any way to find places along with the routes.If possible please let me know please sir.
    Thanks

  • Arslanali

    Hi.
    AndroidStudio install(run) in Virt.Dev. (genymotion)

    Installation failed with message INSTALL_FAILED_MISSING_SHARED_LIBRARY.

    It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing.

    WARNING: Uninstalling will remove the application data!

    Do you want to uninstall the existing application?

  • Mehul Gajjar

    hi i followed your tutorial its working perfectly but

    i am working with 2 languages english and arabic i want to display map as per user language selection.

    i am getting issue when i select arabic language and update language but google map is not change in arabic but when i remove app from recent app and then again open it then it will update google map into arabic. by getting value from shared-preference.

    i am using this code

    String templng = myPrefrence.getStringReponse(Config.LANGUAGE);

    if(templng.equals(“en-us”))

    {

    String languageToLoad = “en-us”; // your language

    Locale locale = new Locale(languageToLoad);

    Locale.setDefault(locale);

    Configuration config = new Configuration();

    config.locale = locale;

    getActivity().getApplicationContext().getResources().updateConfiguration(config,

    getActivity().getApplicationContext().getResources().getDisplayMetrics());

    }

    else

    {

    String languageToLoad = “ar”; // your language

    Locale locale = new Locale(languageToLoad);

    Locale.setDefault(locale);

    Configuration config = new Configuration();

    config.locale = locale;

    getActivity().getApplicationContext().getResources().updateConfiguration(config,

    getActivity().getApplicationContext().getResources().getDisplayMetrics());

    }

    • NikzArkz

      Can you please share your code? I tried so hard and this is very urgent for my university project.

  • RAMDdFLEET

    hey!!
    I m getting error in the PlacesList.java file.

    these are the following errors
    1 setContentView(R.layout.map_places);
    2 mapView = (MapView) findViewById(R.id.mapView);

    I inferred that there are some errors with the resources and layouts.

    Whether you missed to mention something?
    Could you help to fix it?

  • meghna

    Hello Sir,

    I need help, I am creation browser key and paste into GooglePlace.java and Android key into map_place.xml
    but I am getting error access denied. List and map not display . plz plz plz help me as early as possible.
    email : meghashine22@gmail.com

  • Karthik thumathy

    Hello sir,
    please replace all eclipse project to android studio.

  • Nishchit Mahajan

    hello ravi, can u post a new video on “Android Working with Google Places and Maps Tutorial”. Mostly all the methods used are deprecated now. It would be a real help if you could do that.

  • narendra kumar

    Hi Sir, I’ve a problem import com.google.api.client.http.json.JsonHttpParser;

    don’t works.
    After adding google-client-http-gson–1.21.0.jar in libs.
    Android Studio say to me: The import com.google.api.client.http.json.JsonHttpParser cannot be resolved.

    Please any one help me urgent.

  • Jainam Mehta

    I can’t import map’s and api’s pls help me urgent

  • nyded

    Hi, tanks for this tutoriel.
    I want to receive my own places, instead of places provided by google . Is it possible to do that ?

    • Sharkes Monken

      Based on your current location google map api serves you with closest known places unless you want to create your map api guess you can retrieve your own places as you want.

  • Vaibhav More

    Hii ravi sir!!! Sir I copied the soure code and modified the places but the application is not working on my android phone… It is giving error Unfotunately the app has stoped!!! Pls help sir

  • fixit

    how to download this project…i couldn’t find any option as such

  • Prathap

    I coultn’t able to import this project into studio…it pops me error as failed migrate coz it is not using gradle build…what shld i do..?? to make it working

  • sanjay singh

    hi ravi ,
    unable to download this project if possible send me the source code in
    developersanjay19@gmail.com

  • Iman marashi

    How to implement this project by map V2?

  • Sparker0i

    Bro, is this code available on GitHub too ?

  • Parimal Debbarma

    How to build this in Android studio any suggestion please ?

  • tuneer mahatpure

    hello sir, can you help me with my code…i want a user input which is a area address and after that i want to show a list of restaurants which is found in that area of 12 km. list of restaurants includes name, address,image,timing etc…thanks in advance

  • mudit srivastava

    map is showing on background

  • shivani

    Need help regarding google maps.
    I am trying to show a directional route between the two marker points.
    But i can see a straight line between the marker points on my map instead of a directional route.
    Please help me solve this issue.
    Awaiting your reply.