Local Search API (Deprecated)

Local Search API Reference

Warning! The Google Local Search API is no longer available. Please migrate to the Google Places API. This documentation remains in place for reference purposes only.

The Google Local Search JavaScript API is a JavaScript library that allows you to embed Google Local Search in your web pages and other web applications. For Flash, and other non-JavaScript environments, the API exposes a raw interface that returns JSON-encoded results that are easily processed by most languages and runtimes. Read more in the JSON Developer's Guide.

Table of Contents

  1. Constructor
  2. Methods
  3. Static methods
  4. Handling search results
    1. Result properties
  5. Troubleshooting

Constructor - google.search.LocalSearch

google.search.LocalSearch produces search results by implementing the google.search.Search interface over the Google Local Search service. Upon completion of a search, it delivers a collection of google.search.LocalResult objects. The google.search.Search base class is not directly used except where noted.

Constructor Description

google.search.LocalSearch

The google.search.LocalSearch constructor allows you to execute searches and receive results from the Local Search service. The methods and properties described below apply to all objects that inherit from this base class. Each of those objects may supply additional interfaces as well.

google.search.LocalSearch is implemented in the following methods, static methods, and properties:

Methods

Method Description

.clearResults()

.clearResults() resets the searcher, clearing all of the results of the previous search. This method is implicitly called prior to executing a new search.

.clearResults() has no arguments and no return value.

.createResultHtml(result)

.createResultHtml(result) allows the caller to either create or re-generate the .html property of the specified result, where result supplies a result object.

If the result has no .html property, this call creates one. One circumstance requiring you to create an .html property is if the caller had previously used .setNoHtmlGeneration().

.createResultHtml() has no return value.

.execute(query)

.execute(query) initiates a new search, where query supplies the search term(s).

This method populates the object with the corresponding set of results, and calls the registered .setSearchCompleteCallback() handler.

.execute() has no return value.

.getAttribution()

.getAttribution() provides an attribution node which is required to be displayed in line with Local Search results. The return value is an HTML node that should be added to each search result. The following snippet demonstrates how to incorporate .getAttribution:

var attribution = google.search.LocalSearch.getAttribution();
if (attribution) {
  var el = document.getElementById("searchwell");
  el.appendChild(attribution);
}

.getResultSetSize()

.getResultSetSize() has no arguments and returns an integer from 1–8 indicating the current result set size (which is established by .setResultSetSize(). It allows you to determine the result set size returned by the search.

.gotoPage(page)

.gotoPage(page) requests a specific page of search results after an initial search completes, where page supplies the page number of the results that the application wants. Numbering of results pages begins at 0, and the searcher returns the first page by default.

If you specify a page number that is out of range, or if the underlying searcher has no .cursor property, no operation is performed.

.gotoPage() has no return value.

.setAddressLookupMode(mode)

By default, the Local Search API co-mingles address lookup results (e.g., NY, NY) with local search results. However, there are situations where this co-mingled approach is undesirable.

For instance, suppose the searcher is centered in Santa Barbara, CA and the user is searching for "Cava". With co-mingled results, the first search result is actually an address match against "Cava Close, Aberdeen City, AB15 UK". The second result is "Cava Restaurant & Bar". Disabling address lookup causes the desired "Cava Restaurant & Bar" to be the first result.

.setAddressLookupMode(mode) allows applications to disable or enable address lookup, where mode supplies the desired address lookup mode:

  • google.search.LocalSearch.ADDRESS_LOOKUP_ENABLED enables address lookup producing co-mingled results. This is the default behavior.
  • google.search.LocalSearch.ADDRESS_LOOKUP_DISABLED disables address lookup and only produces search result titles.

.setAddressLookupMode(mode) has no return value.

.setCenterPoint(location)

.setCenterPoint(location) targets search results to a specific location, where location supplies the location using one of three possible variants:

  • The center point of a map, using google.maps.Map2 in the presence of a getCenter() property.
  • A latitude/longitude combination, using google.maps.LatLng in the presence of an x property.
  • A string which specifies an address by name. When this argument is presented, searches are scoped as if the user performed a Google Local Search specifying near location as part of their search expression. Note: The string location is resolved into a google.maps.LatLng asynchronously so if this method is used, searches are made relative to this location once the geocoding operation completes with success.

If you do not specify this property, the default location is San Francisco, California.

The preferred interface is either google.maps.LatLng() or google.maps.Map2().

.setCenterPoint(location) has no return value.

.setNoHtmlGeneration()

.setNoHtmlGeneration() stops your application from generating an .html property, leaving you with only the raw properties valid in a result. This property is useful for optimizing your application, if you want to handle rendering of the results yourself.

.setNoHtmlGeneration() has no arguments and no return value.

.setQueryAddition(term)

.setQueryAddition(term) sets (or clears) an optional, additional query term that is appended to all queries flowing through the searcher, where term supplies the additional term. Applications typically use this API to provide alternative results with mild variations from the original search term.

To clear an existing query addition, call either .setQueryAddition(null) or .setQueryAddition('').

.setQueryAddition() has no return value.

.setRestriction(type, opt_value)

.setRestriction(type, opt_value) specifies or clears a restriction on the set of results returned by this searcher, where:

  • type (required) has one possible value for local search: google.search.Search.RESTRICT_TYPE.
  • This value is required to set or clear a restriction.
  • opt_value supplies the value for the specified restriction type, as follows:
    • google.search.LocalSearch.TYPE_LOCALONLY_RESULTS returns only local listing results results and geocodes. This is the default behavior.
    • google.search.LocalSearch.TYPE_BLENDED_RESULT returns a mix of both KML results and normal, local listings and geocodes.
    • google.search.LocalSearch.TYPE_KMLONLY_RESULTS returns only KML results and geocodes.

To return the searcher to its default behavior, clear the restriction by calling this method with no opt_value, as follows: .setRestriction(type).

.setRestriction(type, opt_value) has no return value.

The following sample shows how to return only KML results:

localSearch.setRestriction(google.search.Search.RESTRICT_TYPE,
  google.search.LocalSearch.TYPE_KMLONLY_RESULTS)

.setResultSetSize(num)

.setResultSetSize(num) specifies the size of the result set, where num supplies the number of results to display per page, from 1-8.

.setResultSetSize() has no return value.

.setSearchCompleteCallback(object, method, opt_arguments?)

.setSearchCompleteCallback(object, method, opt_arguments?) registers an object and method to notify when a search completes, where:

  • object supplies an application-level object that defines the context in which to call the specified method.
  • method supplies the search completion handler function, which checks for results and appends them to HTML nodes.
  • opt_arguments allows you to optionally pass in a list of arguments, in order, to the specified method. If you choose to use opt_arguments, you must pass in a list (null is also acceptable).

    For example, if you call this method as localSearch.setSearchCompleteCallback(handler, handler.method, [[1, 2, 3]);, then you execute handler.method(1, 2, 3); when the search completes.

In this API, the calls are asynchronous. Therefore, you can't block on the return and then use the results. Rather, you have to use a callback, which will execute a method upon the return of the results.

.setSearchCompleteCallback() has no return value.

Static methods

Static method Description

.computeStaticMapUrl(results, height, width, opt_zoom?)

.computeStaticMapUrl(results, height, width, opt_zoom?) is a utility function that creates a static map image from the a collection of points specified as a collection of search result objects, objects containing a numeric .lat and .lng property, or google.maps.LatLng objects. Only the first google.search.LocalSearch.STATIC_MAP_MAX_POINTS objects are included. This function is defined as follows:

  • results supplies an array of objects to be plotted on on a static map image.
  • height supplies the height of the new image, in pixels (maximum height of 640 pixels). This field is required.
  • width supplies the width of the new image, in pixels (maximum width of 640 pixels). This field is required.
  • opt_zoom supplies an optional zoom level for the map. If not specified, the system computes an appropriate zoom level. If supplied, valid values include:
    • google.search.LocalSearch.STATIC_MAP_ZOOM_CLOSEST
    • google.search.LocalSearch.STATIC_MAP_ZOOM_FARTHEST

.computeStaticMapUrl(results, height, width, opt_zoom?) returns a URL to the static map image.

The code sample below creates a static map image from a collection of locations in northern Europe. This map displays by default when there are no search results. When a search completes, a new map image is computed using the collection of search results.

// demonstrate computeStaticMapUrl with simple point array
this.worldPointsUrl = google.search.LocalSearch.computeStaticMapUrl(
                        worldPoints,350, 400);
document.getElementById("resultsImg").src =
                        this.worldPointsUrl;
...
var worldPoints = [
  { lat : 48.8565, lng : 2.3509 },      // paris
  { lat : 52.5238, lng : 13.4119},      // berlin
  { lat : 52.3738, lng : 4.8909},       // amsterdam
  { lat : 55.676294, lng : 12.568115},  // copenhagen
  { lat : 60.160791, lng : 24.952548},  // helsinki
  { lat : 59.332725, lng : 18.064454},  // stockholm
  { lat : 59.913820, lng : 10.738741}   // oslo
];

.getBranding(opt_element?, opt_orientation?)

.getBranding(opt_element?, opt_orientation?) is a static helper function that returns a "powered by Google" HTML DOM branding node to your application, and optionally attaches it to your document as the only child of the specified optional element. The purpose of this method is to ensure that your application has a simple way to comply with branding requirements.

The branding node, by default, is designed for a horizontal orientation and works well underneath a search form, above or below a collection of results, etc.

  • opt_element is an optional argument which, if supplied, specifies the HTML DOM node that will be populated with a "powered by Google" branding element.
  • opt_orientation - an optional argument which, if supplied, specifies the orientation of the branding node. Valid values include:
    • google.search.Search.HORIZONTAL_BRANDING requests horizontal orientation. This is the default behavior.
    • google.search.Search.VERTICAL_BRANDING requests vertical orientation.

.getBranding() returns a "powered by Google" HTML DOM node that you can attach or clone onto your document.

You must call .getBranding() on google.search.Search, not on google.search.LocalSearch.

Warning! This API requires displaying attribution near any API input boxes and the display of results, indicating that it is "Powered by Google". If you choose not to use .getBranding(), you are obligated to provide this branding yourself.

.resizeStaticMapUrl(result, height, width, opt_zoom?)

.resizeStaticMapUrl(result, height, width, opt_zoom?) is a utility function that resizes the image associated with the staticMapUrl property of the specified result. Upon completion, this property is replaced with a new value that represents the re-sized static map image. This function is defined as follows:

  • result supplies the result object whose static map image is to be re-sized. Upon completion, the staticMapUrl property of this result object is modified.
  • height supplies the new image height, in pixels (maximum height of 640 pixels). This field is required.
  • width supplies the new image width width, in pixels (maximum width of 640 pixels). This field is required.
  • opt_zoom supplies an optional zoom level for the map, defined as follows:
    • If you don't specify a zoom, the value is unchanged. The default value is google.search.LocalSearch.STATIC_MAP_ZOOM_DEFAULT.
    • google.search.LocalSearch.STATIC_MAP_ZOOM_CLOSEST defines the closest zoom
    • google.search.LocalSearch.STATIC_MAP_ZOOM_FARTHEST defines the furthest zoom

.resizeStaticMapUrl(result, height, width, opt_zoom?) returns the new value of the resized staticMapUrl.

The snippet below demonstrates one way to use this method.

var img = document.createElement("img");
google.search.LocalSearch.resizeStaticMapUrl(result, 80, 120);
img.src = result.staticMapUrl;
img.title = result.titleNoFormatting;

.setOnLoadCallback(callback)

.setOnLoadCallback(callback) is a static function that registers the specified handler function to be called once the page containing this call loads, where callback is a required function called when the containing document is loaded and the API is ready for use (e.g., after onLoad). This function is implemented on the google namespace (i.e., google.setOnLoadCallback(callback);)

.setOnLoadCallback() has no return value.

Note: Previous documentation recommended that you use the body element's onload attribute (<body onload="OnLoad()">). While this is a fine way to go when you are in complete control of the page and all code loaded by the page, this approach can cause problems with some runtimes that destroy your body.onload handler. setOnLoadCallback() does not have these problems, and therefore is the recommended method of registering a callback that calls your code when the API is fully loaded and ready for use.

Handling search results

Result objects are produced using a JSON encoding of server search requests. Consequently, we have chosen not to implement formal JavaScript objects, and instead dynamically create these objects from their serialized form.

While there is no formal implementation of the objects, they exist, and we document them as if there was a backing JavaScript implementation. The impact of all this is minimal. All that it means is that there is no named constructor. For each result, it's as if the system called new Object() and then set formal properties on that object. These properties are documented below.

Important note: Maximum number of search results

The Google Local Search API allows a maximum of 32 results on 4 pages. There is no way to get more than 32 results.

Result properties

Here are the basic properties allowing you to handle results from the Local Search API.

Property Description

addressLines[]

Supplies an array consisting of the mailing address lines for this result, for instance: ["1600 Amphitheatre Pky", "Mountain View, CA 94043"] or ["Via del Corso, 330", "00186 Roma (RM), Italy"]. To correctly render an address associated with a result, either directly use the .html property of the result or iterate through this array and display each addressLine in turn.

city

Supplies the city name for the result.

Note: If a city name is not available, this property may be set to "".

content

For KML results, this property contains a content snippet associated with the KML result.

Note: For local results, set this property to "".

country

Supplies a country name for the result.

Note: If the country name is not specified, set this property to "".

cursor

.cursor is an optional property that is present once a search completes successfully. When present, the property specifies how an application can request additional search results for the current query term, the estimated result count, the current page, and the URL for a search results page. The property has the following structure:

  • pages[] supplies an array used by start in order to iterate through all available results. Each entry in the array is an object with the following structure:
    • start supplies the value that will be used in the &start URL argument to request a bundle of results
    • label supplies a text label associated with the entry (for example, "1", "2", "3", or "4")
  • estimatedResultCount supplies the estimated number of results that match the current query. This value will not necessarily match the similar value that is visible on the Google.com search properties.
  • currentPageIndex supplies the index into the pages array of the current set of results.
  • moreResultsUrl supplies a URL to a Google-hosted search page that contains additional search results.

Note: The Local Searcher supports a maximum of 8 result pages. When combined with subsequent requests, a maximum total of 64 results are available. It is not possible to request more than 64 results.

ddUrl

Supplies a URL that you can use to provide driving directions from the center of the set of search results to this search result.

Note: If a region is not available, this property may be missing or null. Always wrap access within a a test of if (result.ddUrl && result.ddUrl != null).

ddUrlToHere

Supplies a URL that can be used to provide driving directions to a search result from a user-specified location.

Note: In some cases, this property may be missing or null. Always wrap access within a a test of if (result.ddUrlToHere && result.ddUrlToHere != null).

ddUrlFromHere

Supplies a URL that can be used to provide driving directions from this search result to a user-specified location.

Note: In some cases this property may be missing or null. Always wrap access within a a test of if (result.ddUrlFromHere && result.ddUrlFromHere != null).

gsearchResultClass

Indicates the type of result (for example, google.search.LocalSearch.RESULT_CLASS indicates GlocalResult).

html

Supplies the root of an HTML element that may be cloned and attached somewhere into the application's DOM hierarchy. We expect that this is the primary property that applications will use, typically by cloning this node and attaching it to the DOM hierarchy.

We expect applications to control styling, as well as which elements are displayed, using CSS. For instance, we expect the following fragment to be common across all applications that wish to copy and paste search results delivered through the Local Search API.

// clone the .html node from the result
var node = result.html.cloneNode(true);

// attach the node into my dom
container.appendChild(node);

lat

Supplies the latitude value of the result. This may be used to construct a GPoint using the following code snippet:

p = new GPoint(parseFloat(result.lng), parseFloat(result.lat));

listingType

This property indicates the type of this result, which can either be "local" (in the case of a local business listing or geocode result), or "kml" in the case of a KML listing.

lng

Supplies the longitude value of the result. This may be used to construct a GPoint as follows:

p = new GPoint(parseFloat(result.lng), parseFloat(result.lat));

phoneNumbers

Supplies an array of phone number objects where each object contains a .type property and a .number property. The value of the .type property can be "main", "fax", "mobile", "data", or "".

region

Supplies a region name for the result. In the US, the region name is typically a state abbreviation; in other areas it might be a province or other region name as locally applicable.

Note: If a region name is not available, this property is set to "".

results[]

.results[] contains an array of search result objects, one for each result. Each time a search executes, this property is cleared, and each time a search completes, the array is populated. If there are no results to report, the .length property of this array will be set to 0. Therefore, results will never be null, and you can always safely check for results.length == 0.

  • The GlocalResult object is produced by google.search.LocalSearch. It is available in that object's .results[] array.
  • This object is indicated by a .GsearchResultClass value of google.search.LocalSearch.RESULT_CLASS.

staticMapUrl

Supplies the URL for a static map image representation of the current result. The image is 150px wide by 100px tall with a single marker representing the current location. Expected usage is to hyperlink this image using the url property. You can resize the image using google.search.LocalSearch.resizeStaticMapUrl().

streetAddress

Supplies the street address and number for the given result.

Note: If no street address is available, this property is set to "".

title

Supplies the title for the result. In some cases, the title and the streetAddress are the same. This typically occurs when the search term is a street address such as 1231 Lisa Lane, Los Altos, CA.

titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., <b>, <i>, etc.). In some cases, the title and the streetAddress are the same. This typically occurs when the search term is a street address such as 1231 Lisa Lane, Los Altos, CA.

url

Supplies the URL to a Google Maps Place page associated with the search result.

Troubleshooting

If you encounter problems with your code:

  • Make sure your API key is valid.
  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. Google Chrome has a full set of developer tools. In Firefox, you can use the JavaScript console or the Firebug. In IE, you can use the Microsoft Script Debugger.
  • Search the discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

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.