Google Maps JavaScript API v3

Places Library

  1. Overview
  2. Loading the Library
  3. Place Searches
    1. Nearby Search Requests
    2. Radar Search
    3. Text Search Requests
    4. Search Responses
    5. Accessing Additional Results
  4. Place Details
    1. Place Details Requests
    2. Place Details Responses
  5. Places Photos

Overview

The Google Places JavaScript library's functions enable your application to search for Places (defined in this API as establishments, geographic locations, or prominent points of interest) contained within a defined area, such as the bounds of a map, or around a fixed point.

The Google Places API offers an autocomplete feature which you can use to give your applications the type-ahead-search behavior of the Google Maps search field. When a user starts typing an address, autocomplete will fill in the rest. For more information, see the autocomplete documentation.

Loading the Library

The Places service is a self-contained library, separate from the main Maps API JavaScript code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=true_or_false"></script>

See the Libraries Overview for more information.

Logo Requirements

If your application displays Places API data on a map, that map must be provided by Google.

If your application displays Places API data on a page or view that does not also display a Google Map, you must show a "Powered by Google" logo with that data. For example, if your application displays a list of Places on one tab, and a Google Map with those Places on another tab, the first tab must show the "Powered by Google" logo.

For use on a white background For use on any non-white background

The following ZIP file contains the "Powered by Google" logo in the correct sizes for desktop, Android and iOS applications. You may not resize or modify these logos in any way.

Download: powered-by-google.zip

Place Searches

With the Places Service you can perform four kinds of searches:

  • Nearby Search returns a list of nearby Places based on a user's location.
  • Radar Search returns a large list of Places within a specified search radius, but with less detail than either Nearby Search or Text Search.
  • Text Search returns a list of nearby Places based on a search string, eg. "Pizza".
  • Place Details requests return more detailed information about a specific Place, including user reviews.

The information returned can include establishments — such as restaurants, stores, and offices — as well as 'geocode' results, which indicate addresses, political areas such as towns and cities, and other points of interest.

Nearby Search Requests

A Nearby Search lets you search for Places within a specified area by keyword or type. A Nearby Search must always include a location, which can be specified in one of two ways:

  • a LatLngBounds.
  • a circular area defined as the combination of the location property — specifying the center of the circle as a LatLng object — and a radius, measured in meters.

A Places Nearby search is initiated with a call to the PlacesService's nearbySearch() method, which will return an array of PlaceResult objects. Note that the nearbySearch() method replaces the search() method as of version 3.9.

service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);

This method takes a request with the following fields:

  • Either of:
    • bounds, which must be a google.maps.LatLngBounds object defining the rectangular search area; or
    • a location and a radius; the former takes a google.maps.LatLng object, and the latter takes a simple integer, representing the circle's radius in meters. The maximum allowed radius is 50 000 meters.
  • keyword (optional) — A term to be matched against all available fields, including but not limited to name, type, and address, as well as customer reviews and other third-party content.
  • minPriceLevel and maxPriceLevel (optional) — Restricts results to only those places within the specified range. Valid values range between 0 (most affordable) to 4 (most expensive), inclusive.
  • name (optional) — A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. Note that a Place may have additional names associated with it, beyond its listed name. The API will try to match the passed name value against all of these names; as a result, Places may be returned in the results whose listed names do not match the search term, but whose associated names do.
  • openNow (optional) — A boolean value, indicating that the Places service should only return those Places that are open for business at the time the query is sent. Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query. Setting openNow to false has no effect.
  • rankBy (optional) — Specifies the order in which results are listed. Possible values are:
    • google.maps.places.RankBy.PROMINENCE (default). This option sorts results based on their importance. Ranking will favor prominent places within the set radius over nearby places that match but that are less prominent. Prominence can be affected by a Place's ranking in Google's index, the number of Place Bumps from your application, global popularity, and other factors. When google.maps.places.RankBy.PROMINENCE is specified, the radius parameter is required.
    • google.maps.places.RankBy.DISTANCE. This option sorts results in ascending order by their distance from the specified location (required). A custom radius and/or bounds is not supported in conjunction with RankBy.DISTANCE. When RankBy.DISTANCE is specified, one or more of keyword, name, or types is required.
  • types (optional) — An array containing one or more of the supported types listed in the Google Places API: Supported Place Types list. The service will return results that match any of the specified types.

You must also pass a callback method to nearbySearch(), to handle the results object and google.maps.places.PlacesServiceStatus response.

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '500',
    types: ['store']
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}

View example (place-search.html)

Radar Search Requests

A Radar Search lets you search for Places within a specified search radius by keyword, type or name. The Radar Search will return more results than a Nearby Search or Text Search, but the results will contain less detail - only the Place reference and a LatLng object. You can get more information about any of the Places in the response with the PlacesService.getDetails() method.

A Places Radar Search is initiated with a call to the PlacesService's radarSearch() method, which will return an array of up to 200 PlaceResult objects. PlaceResult objects returned by radarSearch() will only include the geometry.location and reference properties.

service = new google.maps.places.PlacesService(map);
service.radarSearch(request, callback);

This method takes a request with the following fields:

  • Either of:
    • bounds, which must be a google.maps.LatLngBounds object defining the rectangular search area; or
    • a location and a radius; the former takes a google.maps.LatLng object, and the latter takes a simple integer, representing the circle's radius in meters. The maximum allowed radius is 50 000 meters.
  • At least one of:
    • keyword (optional) — A term to be matched against all available fields, including but not limited to name, type, and address, as well as customer reviews and other third-party content.
    • name (optional) — A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. Note that a Place may have additional names associated with it, beyond its listed name. The API will try to match the passed name value against all of these names; as a result, Places may be returned in the results whose listed names do not match the search term, but whose associated names do.
    • types (optional) — An array containing one or more of the supported types listed in the Google Places API: Supported Place Types list. The service will return results that match any of the specified types.
  • Optionally:
    • minPriceLevel and maxPriceLevel (optional) — Restricts results to only those places within the specified price level. Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive.
    • openNow — A boolean value, indicating that the Places service should only return those Places that are open for business at the time the query is sent. Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query. Setting openNow to false has no effect.

You must also pass a callback method to radarSearch(), to handle the PlaceResults object and google.maps.places.PlacesServiceStatus.

var map;
var service;

function initialize() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: new google.maps.LatLng(-33.8668283734, 151.2064891821),
    zoom: 15
  });

  infoWindow = new google.maps.InfoWindow();
  service = new google.maps.places.PlacesService(map);

  google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}

function performSearch() {
  var request = {
    bounds: map.getBounds(),
    keyword: 'best view'
  };
  service.radarSearch(request, callback);
}

function callback(results, status) {
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    alert(status);
    return;
  }
  for (var i = 0, result; result = results[i]; i++) {
    var marker = new google.maps.Marker({
      map: map,
      position: result.geometry.location
    });
  }
}

google.maps.event.addDomListener(window, 'load', initialize);

View example (place-radar-search.html)

Text Search Requests

The Google Places Text Search Service is a web service that returns information about a set of Places based on a string — for example "pizza in New York" or "shoe stores near Ottawa". The service responds with a list of Places matching the text string and any location bias that has been set. The search response will include a list of Places. You can send a Place Details request for more information about any of the Places in the response.

Text Searches are initiated with a call to the PlacesService's textSearch() method.

service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);

This method takes a request with the following fields:

  • query (required) The text string on which to search, for example: "restaurant". The Places service will return candidate matches based on this string and order the results based on their perceived relevance.
  • Optionally:
    • openNow — A boolean value, indicating that the Places service should only return those Places that are open for business at the time the query is sent. Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query. Setting openNow to false has no effect.
    • minPriceLevel and maxPriceLevel — Restricts results to only those places within the specified price level. Valid values are in the range from 0 (most affordable) to 4 (most expensive), inclusive.
    • Either of:
      • bounds — A google.maps.LatLngBounds object defining the rectangle in which to search; or
      • a location and a radius — You may bias results to a specified circle by passing a location and a radius parameter. This will instruct the Places service to prefer showing results within that circle. Results outside the defined area may still be displayed. The location takes a google.maps.LatLng object, and the radius takes a simple integer, representing the circle's radius in meters. The maximum allowed radius is 50 000 meters.
    • types — An array containing one or more of the supported types listed in the Google Places API: Supported Place Types list. The service will return results that match any of the specified types.

You must also pass a callback method to textSearch(), to handle the results object and a google.maps.places.PlacesServiceStatus response.

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '500',
    query: 'restaurant'
  };

  service = new google.maps.places.PlacesService(map);
  service.textSearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}

Search Responses

Status Codes

The PlacesServiceStatus response object contains the status of the request, and may contain debugging information to help you track down why the Place request failed. Possible status values are:

  • ERROR: There was a problem contacting the Google servers.
  • INVALID_REQUEST: This request was invalid.
  • OK: The response contains a valid result.
  • OVER_QUERY_LIMIT: The webpage has gone over its request quota.
  • REQUEST_DENIED: The webpage is not allowed to use the PlacesService.
  • UNKNOWN_ERROR: The PlacesService request could not be processed due to a server error. The request may succeed if you try again.
  • ZERO_RESULTS: No result was found for this request.

Place Search Results

The nearbySearch() and textSearch() functions return an array of PlaceResult objects. Each PlaceResult object has the following properties:

  • formatted_address is a string containing the human-readable address of this place. Often this address is equivalent to the "postal address". The formatted_address property is only returned for a Text Search.
  • geometry: The Place's geometry-related information. This includes:
    • location provides the latitude and longitude of the Place.
    • viewport defines the preferred viewport on the map when viewing this Place.
  • html_attributions: An array of attributions that you should display when displaying the search results. Each entry in the array contains the HTML text for a single attribution. Note: This is an aggregation of all the attributions for the entire search response. All PlaceResult objects in the response therefore contain identical attribution lists.
  • icon: URL to an image resource that can be used to represent this Place's type.
  • id: contains a unique identifier denoting this place. This identifier may not be used to retrieve information about this place, but can be used to consolidate data about this Place, and to verify the identity of a Place across separate searches. As ids can occasionally change, it's recommended that the stored id for a Place be compared with the id returned in later Details requests for the same Place, and updated if necessary.
  • name: The Place's name.
  • opening_hours may contain the following information:
    • open_now is a boolean value indicating if the Place is open at the current time.
  • rating contains the Place's rating, from 0.0 to 5.0, based on user reviews.
  • reference contains a token that can be used to query the Details service in future. This token may differ from the reference used in the request to the Details service. It is recommended that stored references for Places be regularly updated. Although this token uniquely identifies the Place, the converse is not true: a Place may have many valid reference tokens.
  • types: An array of types for this Place (e.g., ["political", "locality"] or ["restaurant", "establishment"]).
  • vicinity: A simplified address for the Place, including the street name, street number, and locality, but not the province/state, postal code, or country. For example, Google's Sydney, Australia office has a vicinity value of 5/48 Pirrama Road, Pyrmont.

Accessing Additional Results

By default, each Place search returns up to 20 establishment results per query; however, each search can return as many as 60 results, split across three pages. Additional pages are available via the PlaceSearchPagination object. In order to access additional pages you must capture the PlaceSearchPagination object via a callback function. The PlaceSearchPagination object is defined as:

  • hasNextPage a boolean property that indicates if further results are available. true when there is an additional results page.
  • nextPage() a function that will return the next set of results. After executing a search, you must wait two seconds before the next page of results will be available.

To see the next set of results, call nextPage. Each page of results must be displayed before displaying the next page of results. Note that each search counts as a single request against your usage limits.

The example below demonstrates how to alter your callback function to capture the PlaceSearchPagination object, so that you can issue multiple search requests.

var map;
var service;
var resultList;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '5000',
    types: ['store']
  };

  service = new google.maps.places.PlacesService(map);

  service.nearbySearch(request, function(results, status, pagination) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
     return;
    }
    resultList.addPlaces(results);
    if (pagination.hasNextPage) {
      resultList.button.onClick = pagination.nextPage;
    }
  });
}

View example (place-search-pagination.html)

Place Details

In addition to providing a list of Places within an area, the Places service can also return detailed information about a specific Place. Once a Place has been returned in a Place Search response, its reference property can be used to request additional details about that Place, such as its complete address, phone number, user rating and reviews, etc.

Place Details Requests

Place Details are requested with a call to the service's getDetails() method.

service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);

This method takes a request, containing the desired Place's reference value.

It also takes a callback method, which needs to handle the status code passed in the google.maps.places.PlacesServiceStatus response, as well as the google.maps.places.PlaceResult object.

var request = {
  reference: 'CnRkAAAAGnBVNFDeQoOQHzgdOpOqJNV7K9-c5IQrWFUYD9TNhUmz5-aHhfqyKH0zmAcUlkqVCrpaKcV8ZjGQKzB6GXxtzUYcP-muHafGsmW-1CwjTPBCmK43AZpAwW0FRtQDQADj3H2bzwwHVIXlQAiccm7r4xIQmjt_Oqm2FejWpBxLWs3L_RoUbharABi5FMnKnzmRL2TGju6UA4k'
};

service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);

function callback(place, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    createMarker(place);
  }
}

View example (place-details.html)

Place Details Responses

Status Codes

The PlacesServiceStatus response object contains the status of the request, and may contain debugging information to help you track down why the Place Details request failed. Possible status values are:

  • ERROR: There was a problem contacting the Google servers.
  • INVALID_REQUEST: This request was invalid.
  • OK: The response contains a valid result.
  • OVER_QUERY_LIMIT: The webpage has gone over its request quota.
  • NOT_FOUND The referenced location was not found in the Places database.
  • REQUEST_DENIED: The webpage is not allowed to use the PlacesService.
  • UNKNOWN_ERROR: The PlacesService request could not be processed due to a server error. The request may succeed if you try again.
  • ZERO_RESULTS: No result was found for this request.

Place Details Results

A successful getDetails() call returns a PlaceResult object with the following properties:

  • address_components: The collection of address components for this Place's location. See the Geocoding service's Address Component Types section for more details.
  • formatted_address: The Place's full address.
  • formatted_phone_number: The Place's phone number, formatted according to the number's regional convention.
  • geometry: The Place's geometry-related information. This includes:
    • location provides the latitude and longitude of the Place.
    • viewport defines the preferred viewport on the map when viewing this Place.
  • html_attributions: Attribution text to be displayed for this Place result.
  • icon: URL to an image resource that can be used to represent this Place's type.
  • id: contains a unique identifier denoting this place. This identifier may not be used to retrieve information about this place, but can be used to consolidate data about this Place, and to verify the identity of a Place across separate searches. As ids can occasionally change, it's recommended that the stored id for a Place be compared with the id returned in later Details requests for the same Place, and updated if necessary.
  • international_phone_number contains the Place's phone number in international format. International format includes the country code, and is prefixed with the plus (+) sign. For example, the international_phone_number for Google's Sydney, Australia office is +61 2 9374 4000.
  • name: The Place's name.
  • utc_offset contains the number of minutes this Place’s current timezone is offset from UTC. For example, for Places in Sydney, Australia during daylight saving time this would be 660 (+11 hours from UTC), and for Places in California outside of daylight saving time this would be -480 (-8 hours from UTC).
  • opening_hours contains the following information:
    • open_now is a boolean value indicating if the Place is open at the current time.
    • periods[] is an array of opening periods covering seven days, starting from Sunday, in chronological order. Each period contains:
      • open contains a pair of day and time objects describing when the Place opens:
        • day a number from 0–6, corresponding to the days of the week, starting on Sunday. For example, 2 means Tuesday.
        • time may contain a time of day in 24-hour hhmm format (values are in the range 0000–2359). The time will be reported in the Place’s timezone.
      • close may contain a pair of day and time objects describing when the Place closes. Note: If a Place is always open, the close section will be missing from the response. Applications can rely on always-open being represented as an open period containing day with value 0 and time with value 0000, and no close.
  • photos[]: an array of PlacePhoto objects. A PlacePhoto can be used to obtain a photo with the getUrl() method, or you can inspect the object for the following values:
    • height: the maximum height of the image, in pixels.
    • width: the maximum width of the image, in pixels.
    • html_attributions: Attribution text to be displayed with this Place photo.
  • rating: The Place's rating, from 0.0 to 5.0, based on user reviews.
  • reference contains a token that can be used to query the Details service in future. This token may differ from the reference used in the request to the Details service. It is recommended that stored references for Places be regularly updated. Although this token uniquely identifies the Place, the converse is not true: a Place may have many valid reference tokens.
  • reviews an array of up to five reviews. Each review consists of several components:
    • aspects[] contains an array of PlaceAspectRating objects, each of which provides a rating of a single attribute of the establishment. The first object in the array is considered the primary aspect. Each PlaceAspectRating is defined as:
      • type the name of the aspect that is being rated. The following types are supported: appeal, atmosphere, decor, facilities, food, overall, quality and service.
      • rating the user's rating for this particular aspect, from 0 to 3.
    • author_name the name of the user who submitted the review. Anonymous reviews are attributed to "A Google user". If a language parameter was set, then the phrase "A Google user" will return a localized string.
    • author_url the URL to the users Google+ profile, if available.
    • language an IETF language code indicating the language used in the user's review. This field contains the main language tag only, and not the secondary tag indicating country or region. For example, all the English reviews are tagged as 'en', and not 'en-AU' or 'en-UK' and so on.
    • rating the user's overall rating for this Place. This is a whole number, ranging from 1 to 5.
    • text the user's review. When reviewing a location with Google Places, text reviews are considered optional; therefore, this field may by empty.
  • types: An array of types for this Place (e.g., ["political", "locality"] or ["restaurant", "establishment"]).
  • url: URL of the associated Google Place Page.
  • vicinity: A simplified address for the Place, including the street name, street number, and locality, but not the province/state, postal code, or country. For example, Google's Sydney, Australia office has a vicinity value of 5/48 Pirrama Road, Pyrmont. The vicinity property is only returned for a Nearby Search.
  • website lists the authoritative website for this Place, such as a business' homepage.

Multidimensional ratings may not be available for all locations. If there are too few reviews then the details response will either include a legacy rating on a 0.0 to 5.0 scale (if available) or no rating at all.

Places Photos

The Places Photo feature allows you to easily add high quality photographic content to your site. The Photo service gives you access to the millions of photos stored in the Places and Google+ Local database. When you search for Places using either a Place Search or Place Details request, photo references will be returned for relevant photographic content. You can access the referenced photos, and resize the image to the optimal size for your application.

An array of PlacePhoto objects will be returned as part of the PlaceResult object for any getDetails() or nearbySearch() request made against a PlacesService. You can request the url for the associated image by calling the PlacePhoto.getUrl() method, and passing a valid PhotoOptions object. The PhotoOptions object allows you to specify the maximum desired height and width of the image. If you specify a value for both max_height and a max_width, the photo service will resize the image to the smaller of the two sizes, while maintaining the original aspect ratio.

The below code snippet accepts a Place object, and adds a marker to the map if a photo exists. The default marker image is replaced by a small version of the photo.

function createPhotoMarker(place) {
  var photos = place.photos;
  if (!photos) {
    return;
  }

  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    title: place.name,
    icon: photos[0].getUrl({'maxWidth': 35, 'maxHeight': 35})
  });
}

Authentification requise

Vous devez être connecté à Google+ pour effectuer cette opération.

Connexion en cours…

Le site Google pour les développeurs a besoin de votre autorisation pour effectuer cette opération.