How to use Google Places and show places in Google Maps within Android

If you are searching to a coordinate (such as street, house number, location…) in Google Maps , you’ll see that there are more information about public places near by such as airport, cafe, restaurant, store… This information is really helpful, for example, if I want to move to a new apartment, I would like to check if the public transport is near by, any supermarket is available, playground for my children is not too far… with Google Maps you’ll get all information. Or another example, if I’m on highway and too tired because of driving, I can find any motel/hotel near by my current location so that I can drop in and take a rest. Therefore today I would like to make a small demo to show how we can show Google Places on our Android smartphone or integrate this feature to our apps.

1. Prerequisites

– Before starting,  I recommend you to read these two posts first How to install Google Maps in Android Emulator and Google Cloud Messaging, ASP.NET Web Api and Android client. I will skip many steps in this post which were already mentioned in the other ones, so read carefully those posts before continuing.

– Whenever you want to use a Google Service API, remember to go to

https://code.google.com/apis/console 

and turn that service on. It’s same for Google Places. Go Google APIs console, on the left of panel –> Services –> Turn Places API on

Turn on Places API

The Google Places API has the following query limits:
– Users with an API key are allowed 1 000 requests per 24 hour period.
– Users who have verified their identity through the APIs console are allowed 100 000 requests per 24 hour period. A credit card is required for verification, by enabling billing in the console. Google Places asks for your credit card purely to validate your identity. Your card will not be charged for use of the Places API.

Indeed I don’t use credit card so I have no choice. 🙂 . I have to use a free one without credit card with 1000 requests per day.

2. Intermediate ASP.NET Web API server

– Create an API key to authorize your services with Google (read post How to install Google Maps in Android Emulator to see how you can create it).
– I refer using a browser key because it will be kept safely at my server. Using Android key has a risk that someone can steal my keys and does things that only god knows. Therefore, I have created a browser key and I will parse Google Places service inside my server. That means, instead of calling Google Places directly, phone will call my service and my service will relay that call to Google Places. Remember that you can only use this kind of service for your own apps, don’t distribute to any other apps. You’ll violate Google TOS when republishing Google Service.
– So let’s start ASP.NET Web API project in Visual Studio and create your own proxy service. You can also use my sample one at

http://restwebserviceforandroid.apphb.com/api/googleplaces

The sample code of GooglePlaces controller is below

public class GooglePlacesController : ApiController
{
	public IList Get(string latitude, string longitude, string radius, string types = "", string name = "")
	{
		IList result = new List();

		NameValueCollection parameters = new NameValueCollection();

		parameters.Add("key", "YOUR_BROWSER_API_KEY");
		parameters.Add("location", latitude.ToString() + "," + longitude.ToString());
		parameters.Add("radius", radius.ToString());
		parameters.Add("sensor", "false");

		if (!string.IsNullOrWhiteSpace(types))
			parameters.Add("types", types);

		if (!string.IsNullOrWhiteSpace(name))
			parameters.Add("name", name);

		string url = "json?" + string.Join("&", parameters.AllKeys.Select(x => string.Format("{0}={1}", HttpUtility.UrlEncode(x), HttpUtility.UrlEncode(parameters[x]))));
		HttpClient httpClient = new HttpClient();
		httpClient.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/place/nearbysearch/");
		HttpResponseMessage response = httpClient.GetAsync(url).Result;
		if (response.IsSuccessStatusCode)
		{
			result = response.Content.ReadAsAsync().Result.Results;
		}

		return result;
	}

	public GooglePlaceDetail Get(string reference)
	{
		GooglePlaceDetail result = new GooglePlaceDetail();
		NameValueCollection parameters = new NameValueCollection();
		parameters.Add("key", "YOUR_BROWSER_API_KEY");
		parameters.Add("sensor", "false");
		parameters.Add("reference", reference);

		string url = "json?" + string.Join("&", parameters.AllKeys.Select(x => string.Format("{0}={1}", HttpUtility.UrlEncode(x), HttpUtility.UrlEncode(parameters[x]))));

		HttpClient httpClient = new HttpClient();
		httpClient.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/place/details/");
		HttpResponseMessage response = httpClient.GetAsync(url).Result;
		if (response.IsSuccessStatusCode)
		{
			result = response.Content.ReadAsAsync().Result.Result;
		}

		return result;
	}
}

– The controller provides two simple actions, one for getting all places nearby a location and one for getting details of a place. These two actions make HTTP request to Google Places service when receiving request from clients. You can extend the controller with many other functions.
– But how should HTTP request to Google APIs service look like? How many options are there to use? Which parameters are available?…  You can find them all in documentation of Google Places at

https://developers.google.com/places/documentation/ 

Read the documentation carefully and extend the service as much as you want. The JSON format of a nearby search looks like following

JSON format of Google Places nearby search

bases on this format, our objects can be likely the code listing below

public class GooglePlaceNearbySearchResult
{
	public IList Html_Attributions { get; set; }

	public string Status { get; set; }

	public IList Results { get; set; }
}

public class GooglePlace : GooglePlaceBaseModel
{
	public OpeningHour Opening_Hours { get; set; }

	public int Price_Level { get; set; }
}

public class GooglePlaceBaseModel
{
	public Geometry Geometry { get; set; }

	public string Icon { get; set; }

	public string Id { get; set; }

	public string Name { get; set; }

	public IList Photos { get; set; }

	public double Rating { get; set; }

	public string Reference { get; set; }

	public IList Types { get; set; }

	public string Vicinity { get; set; }
}

The code listing above just shows some of value objects. I can’t post complete solution of web service because it contains sensitive information about my server. If you need the others, drop a comment under this post, I will post it for you. That’s all about our service. It’s just a proxy service and redirects the requests to Google, nothing special.

3. Android client

3.1 Activities

In Android demo client, there are 4 activities :
MainActivity where the current GPS location can be set for emulator and one button to show all nearby places

MainActivity to set current GPS location

AllNearbyPlacesActivity all nearby places are found by Google Places service

All nearby places activity

SinglePlaceActivity from AllNearbyPlacesActivity, when you click on single row, details of one single place will be shown in this activity.

Single place activity

GooglePlacesMapActivity all nearby places will be shown in Google Maps

Show places in Google Maps

3.2 GPS service required

– For location access, we need the GPS service enabled. Therefore when app starts, I will check if GPS service or Network Location service is available. If not, I will show a warning dialog.

private void initializeVariables() {
	gpsUtil = new GPSUtil(MainActivity.this);
	gpsUtil.setOnLocationListener(LocationListener);

	if (!gpsUtil.isGPSProviderEnabled() || !gpsUtil.isNetworkProviderEnabled())
	{
		RedirectToLocationServiceSetting();
	}

	gpsUtil.start();
}

Check if location service available

– To set the current location for emulator, you have to connect to it through Telnet and set Geo coordinate with geo fix command

telnet localhost <console-port>
geo fix 151.1957362 -33.8670522 4392

Telnet can be installed under Windows OS with following command “pkgmgr /iu:”TelnetClient””. Remember to start cmd under administrator to be able to run it. The <console-port> can be read from emulator’s windows title.

3.3 Show places in Google Maps

– To display places in Google Maps, you need to read the posts I mentioned above so that you can get Google Maps installed on your emulator.
– For each nearby found place, I will add a red marker for it. Our location will be marked with green flag. The maps will be automatically zoomed to our current position and zoomed to appropriate level so that all places will be visible on screen.

protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);    //To change body of overridden methods use File | Settings | File Templates.
	setContentView(R.layout.google_places_map);

	Intent intent = getIntent();
	latitude = intent.getDoubleExtra(ConstantValues.EXTRA_LATITUDE,0);
	longitude = intent.getDoubleExtra(ConstantValues.EXTRA_LONGITUDE,0);
	googlePlaces = new Gson().fromJson(intent.getStringExtra(ConstantValues.EXTRA_ALL_NEARBY_PLACES), GooglePlace[].class);

	googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
	googleMap.setOnCameraChangeListener(GoogleMapOnCameraChangeListener);
	googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

	LatLng currentLatLng = new LatLng(latitude,longitude);

	MarkerOptions markerOptions = new MarkerOptions();
	markerOptions.position(currentLatLng);
	markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markergreen));
	markerOptions.title("Your current position");
	googleMap.addMarker(markerOptions);

	for(GooglePlace googlePlace:googlePlaces)
	{
		currentLatLng = new LatLng(googlePlace.getGeometry().getLocation().getLat(),googlePlace.getGeometry().getLocation().getLng());
		builder.include(currentLatLng);
		markerOptions = new MarkerOptions();
		markerOptions.position(currentLatLng);
		markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markerred));
		markerOptions.title(googlePlace.getName());
		googleMap.addMarker(markerOptions);
	}

}

private GoogleMap.OnCameraChangeListener GoogleMapOnCameraChangeListener = new GoogleMap.OnCameraChangeListener() {
	@Override
	public void onCameraChange(CameraPosition cameraPosition) {
		googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(),10));
		googleMap.setOnCameraChangeListener(null);
	}
};

4. Conclusion

– I hope that you can now equip your app with Google Places feature. It’ll be nice feature for any app. The post is written for Android emulator, when you have a real device to develop, you can skip some steps (such as install Google Maps because Google Maps is standard app for all Android smartphones). There are still many interesting APIs of Google Places, discover them through documentation and extend your web service to use those APIs.
– Source code of Android client: https://bitbucket.org/hintdesk/android-how-to-use-google-places-and-show-places-in-google
– Source code of util class used in Android client: https://bitbucket.org/hintdesk/android-hintdesk-core

5. Updates

5.1 Update 27.04.2014

– Update Photo class in Android client to get Photo_Reference from JSON

8 thoughts on “How to use Google Places and show places in Google Maps within Android”

  1. Great tutorial. Have you tried to extract the photo_reference from the JSON response yet? I have been trying to do that but have not been able to get that to work yet.

  2. I’d love to have some help on the restful server’s code, it seems to be down at the moment and I can’t get it the app to load the places list – i had the app running perfectly a couple of days ago. Let me know if you can assist on passing on the code for this (I also just donated to your site, I hope this helps as well). Thanks a ton.

  3. Thanks so much for the code, this tutorial has helped me immensely. I appreciate your hard work. Yes it was my fault, the server was indeed working, sorry if I wasted more of your time on this.
    Great tutorial, cheers!
    creationdust

  4. Hi : Recently, we are developing one App that can acquire the nearby place detail including photo. We are trying to follow the source code provided by you. However, when we want to acquire the photos, in the client side, the photo reference is always null. Is that means your server does not set the photo information, so in the client side, we can not get any information about the photo ?

    thank you for answering me.
    Po-Lin Yeh

  5. @Po-Lin Yeh: The server has already set Photo_Reference. When the client has null value of Photo_Reference that means something wrong when converting from JSON to object. I’ll take a look later.

Leave a Reply

Your email address will not be published. Required fields are marked *