Google Places API – Tutorial

The Google Places API is a service that returns information about Places — defined within this API as establishments, geographic locations, or prominent points of interest — using HTTP requests. Place requests specify locations as latitude/longitude coordinates.

The following Place requests are available:

  • Place Searches return a list of Places based on a user’s location or search string.
  • Place Details requests return more detailed information about a specific Place, including user reviews.
  • Place Actions allow you to supplement the data in Google’s Places Database with data from your application. You can schedule Events, add and remove Places, or weight Place rankings from user activity with Place Bumps.
  • Place Photos gives you access to the millions of Place related photos stored in Google’s Place database.
  • Place Autocomplete can be used to automatically fill in the name and/or address of a place as you type.
  • Query Autocomplete can be used to provide a query prediction service for text-based geographic searches, by returning suggested queries as you type.
    Each of the services is accessed as an HTTP request, and returns either an JSON or XML response. All requests to a Place service must use the https:// protocol, and include an API key.

Authentication

The Google Places API uses an API key to identify your application. API keys are managed through the Google APIs Console . You’ll need your own server API key before you can begin using the API. To activate the Places API and create your key:

  • Visit the Google APIs Console at https://code.google.com/apis/console and log in with your Google account.
  • A default project called API Project is created for you when you first log in to the APIs Console. You can use the project, or create a new one by clicking the API Project button at the top of the window and selecting Create. Maps API for Business customers must use the API project created for them as part of their Places for Business purchase.
  • Click the Services link in the left-hand navigation panel.
  • Click the status switch (the on/off button) next to the Places API entry. The switch slides to ON.
  • Click API Access in the left-hand navigation panel.
  • Click Create new key for Android App.

Google Places API

Over the years we have developed several Google Map, mashups Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your multimedia mobile application development project.

Google Places API

Let us take the example to find out the near by places.

To search for specific types of places (such as cafes), you can include the types parameter in your Places Search requests.

https://maps.googleapis.com/maps/api/place/search/json
  ?types=cafe
  &location=37.787930,-122.4074990
  &radius=5000
  &sensor=false
  &key=YOUR_API_KEY

2. Try specifying multiple place types by modifying the URL below to include other place types separated by a pipe ( | ) character in the URL. The Places Search API will return Places associated with any of the types that you specify. The example below demonstrates how to search for places that are considered a cafe or a bakery or both:

https://maps.googleapis.com/maps/api/place/search/json
  ?types=cafe|bakery
  &location=37.787930,-122.4074990
  &radius=5000
  &sensor=false
  &key=YOUR_API_KEY

3. To retrieve places based by distance:

  • 1. Remove the radius parameter from your Place Search request.
  • 2. Add a rankby=distance parameter/value pair.
  • 3. Include one or more of the keyword, name, or types parameters.

For example, the URL below can be used to specify a search for cafes near downtown San Francisco, with results ordered by distance from the location:

https://maps.googleapis.com/maps/api/place/search/json
  ?types=cafe
  &rankby=distance
  &location=37.787930,-122.4074990
  &sensor=false
  &key=YOUR_API_KEY

Place.java :

public class Place {
    private String id;
    private String icon;
    private String name;
    private String vicinity;
    private Double latitude;
    private Double longitude;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public Double getLatitude() {
        return latitude;
    }
    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }
    public Double getLongitude() {
        return longitude;
    }
    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getVicinity() {
        return vicinity;
    }
    public void setVicinity(String vicinity) {
        this.vicinity = vicinity;
    }

    static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
        try {
            Place result = new Place();
            JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
            JSONObject location = (JSONObject) geometry.get("location");
            result.setLatitude((Double) location.get("lat"));
            result.setLongitude((Double) location.get("lng"));
            result.setIcon(pontoReferencia.getString("icon"));
            result.setName(pontoReferencia.getString("name"));
            result.setVicinity(pontoReferencia.getString("vicinity"));
            result.setId(pontoReferencia.getString("id"));
            return result;
        } catch (JSONException ex) {
            Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public String toString() {
        return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
    }

}

PlacesService.java:

public class PlacesService {

 private String API_KEY;

 public PlacesService(String apikey) {
  this.API_KEY = apikey;
 }

 public void setApiKey(String apikey) {
  this.API_KEY = apikey;
 }

 public ArrayList<place> findPlaces(double latitude, double longitude,
   String placeSpacification) {

  String urlString = makeUrl(latitude, longitude, placeSpacification);

  try {
   String json = getJSON(urlString);

   System.out.println(json);
   JSONObject object = new JSONObject(json);
   JSONArray array = object.getJSONArray("results");

   ArrayList<place> arrayList = new ArrayList<place>();
   for (int i = 0; i < array.length(); i++) {
    try {
     Place place = Place
       .jsonToPontoReferencia((JSONObject) array.get(i));
     Log.v("Places Services ", "" + place);
     arrayList.add(place);
    } catch (Exception e) {
    }
   }
   return arrayList;
  } catch (JSONException ex) {
   Logger.getLogger(PlacesService.class.getName()).log(Level.SEVERE,
     null, ex);
  }
  return null;
 }

 // https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=apikey
 private String makeUrl(double latitude, double longitude, String place) {
  StringBuilder urlString = new StringBuilder(
    "https://maps.googleapis.com/maps/api/place/search/json?");

  if (place.equals("")) {
   urlString.append("&location=");
   urlString.append(Double.toString(latitude));
   urlString.append(",");
   urlString.append(Double.toString(longitude));
   urlString.append("&radius=1000");
   // urlString.append("&types="+place);
   urlString.append("&sensor=false&key=" + API_KEY);
  } else {
   urlString.append("&location=");
   urlString.append(Double.toString(latitude));
   urlString.append(",");
   urlString.append(Double.toString(longitude));
   urlString.append("&radius=1000");
   urlString.append("&types=" + place);
   urlString.append("&sensor=false&key=" + API_KEY);
  }
  return urlString.toString();
 }

 protected String getJSON(String url) {
  return getUrlContents(url);
 }

 private String getUrlContents(String theUrl) {
  StringBuilder content = new StringBuilder();
  try {
   URL url = new URL(theUrl);
   URLConnection urlConnection = url.openConnection();
   BufferedReader bufferedReader = new BufferedReader(
     new InputStreamReader(urlConnection.getInputStream()), 8);
   String line;
   while ((line = bufferedReader.readLine()) != null) {
    content.append(line + "\n");
   }
   bufferedReader.close();
  }catch (Exception e) {
   e.printStackTrace();
  }
  return content.toString();
 }
}
</place></place></place>

MainActivity.java:

public class MainActivity extends Activity {

 private final String TAG = getClass().getSimpleName();
 private GoogleMap mMap;
 private String[] places;
 private LocationManager locationManager;
 private Location loc;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initCompo();
  places = getResources().getStringArray(R.array.places);
  currentLocation();
  final ActionBar actionBar = getActionBar();
  actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
  actionBar.setListNavigationCallbacks(ArrayAdapter.createFromResource(
    this, R.array.places, android.R.layout.simple_list_item_1),
    new ActionBar.OnNavigationListener() {
     @Override
     public boolean onNavigationItemSelected(int itemPosition,
       long itemId) {
      if (loc != null) {
       mMap.clear();
       new GetPlaces(MainActivity.this,
         places[itemPosition].toLowerCase().replace(
           "-", "_")).execute();
      }
      return true;
     }
    });
 }

 private class GetPlaces extends AsyncTask<void arraylist="" lace="" void="">> {

  private ProgressDialog dialog;
  private Context context;
  private String places;

  public GetPlaces(Context context, String places) {
   this.context = context;
   this.places = places;
  }

  @Override
  protected void onPostExecute(ArrayList<place> result) {
   super.onPostExecute(result);
   if (dialog.isShowing()) {
    dialog.dismiss();
   }
   for (int i = 0; i < result.size(); i++) {
    mMap.addMarker(new MarkerOptions()
      .title(result.get(i).getName())
      .position(
        new LatLng(result.get(i).getLatitude(), result
          .get(i).getLongitude()))
      .icon(BitmapDescriptorFactory
        .fromResource(R.drawable.pin))
      .snippet(result.get(i).getVicinity()));
   }
                        CameraPosition cameraPosition = new CameraPosition.Builder()
     .target(new LatLng(result.get(0).getLatitude(), result
       .get(0).getLongitude())) // Sets the center of the map to
           // Mountain View
     .zoom(14) // Sets the zoom
     .tilt(30) // Sets the tilt of the camera to 30 degrees
     .build(); // Creates a CameraPosition from the builder
   mMap.animateCamera(CameraUpdateFactory
     .newCameraPosition(cameraPosition));
  }

  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   dialog = new ProgressDialog(context);
   dialog.setCancelable(false);
   dialog.setMessage("Loading..");
   dialog.isIndeterminate();
   dialog.show();
  }

  @Override
  protected ArrayList<place> doInBackground(Void... arg0) {
   PlacesService service = new PlacesService(
     "Put your project browser API key here");
   ArrayList<place> findPlaces = service.findPlaces(loc.getLatitude(), // 28.632808
     loc.getLongitude(), places); // 77.218276


   for (int i = 0; i < findPlaces.size(); i++) {

    Place placeDetail = findPlaces.get(i);
    Log.e(TAG, "places : " + placeDetail.getName());
   }
   return findPlaces;
  }
 }

 private void initCompo() {
  mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
    .getMap();
 }

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

 private void currentLocation() {
  locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

  String provider = locationManager
    .getBestProvider(new Criteria(), false);

  Location location = locationManager.getLastKnownLocation(provider);

  if (location == null) {
   locationManager.requestLocationUpdates(provider, 0, 0, listener);
  } else {
   loc = location;
   new GetPlaces(MainActivity.this,
     places[0].toLowerCase().replace(
       "-", "_")).execute();
   Log.e(TAG, "location : " + location);
  }

 }

 private LocationListener listener = new LocationListener() {

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

  @Override
  public void onProviderEnabled(String provider) {
  }

  @Override
  public void onProviderDisabled(String provider) {
  }

  @Override
  public void onLocationChanged(Location location) {
   Log.e(TAG, "location update : " + location);
   loc = location;
   locationManager.removeUpdates(listener);
  }
 };
}

+++++++++++++++++++

We have considerable experience in developing apps using Google Places API.
Photos – City Guide

Over the years we have developed several advanced Google Places and Google Map based Android and iPhone components, code modules and Frameworks that can work as plug and play solutions for developing new apps that will substantially reduce the app development cost and time.

Contact us to discuss your Google Places or Map based mobile application development project.

Related Posts

Leave a comment

Hey, so you decided to leave a comment! That's great. Just fill in the required fields and hit submit. Note that your comment will need to be reviewed before its published.