Local Search API (Deprecated)

JSON 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 API JSON interface can be used to write local query applications in any language that can handle a JSON-encoded result set with embedded status codes.

Note: The Google Local Search API must be used for user-generated searches. Automated or batched queries of any kind are strictly prohibited.

Contents

  1. Audience
  2. Application requirements
  3. Using the JSON interface
    1. Sending a basic query
    2. Using the callback argument
    3. Using the context argument
  4. Code examples
    1. Using Flash
    2. Using Java
    3. Using PHP
    4. Using Python
    5. Using Perl
  1. JSON reference
    1. Request format
      1. URL base address
      2. URL arguments
    2. Response format
      1. Basic query
      2. Callback argument
      3. Context argument

Audience

The Google Local Search JSON interface, and this guide, are provided for Flash developers, and all other developers who need to access Local Search from other Non-JavaScript environments.

Application requirements

Applications that use this interface must abide by all existing Terms of Service. Most importantly, you must correctly identify yourself in your requests.

Query inputs and results must display "Powered by Google" branding, as described by .getBranding.

Results must display a business listing source attribution as implemented via .getAttribution.

Requests can only be made on behalf of an end user. All results must be displayed.

Applications MUST always include a valid and accurate HTTP referer header in their requests.

Each request contains a valid API Key (not required, but highly encouraged). By providing a key, your application provides us with a secondary identification mechanism that is useful in case we need to contact you to correct any problems. Read more about why it's useful to have an API key.

Your application uses the userip parameter (not required, but highly encouraged). This parameter supplies the IP address of the end-user who made the request and validates that you are not making automated requests in violation of the Terms of Service.

Using the JSON interface

The easiest way to start learning about this interface is to try it out. This section shows how to use the curl command line tool to execute sample queries.

Sending a basic query

curl -e http://www.my-ajax-site.com \
'http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=Palm%20Springs%20CA'

This command performs a local search (/ajax/services/search/local) for Palm Springs, CA (q=Palm%20Springs%20CA). The response has a Content-Type of text/javascript; charset=utf-8.

{"responseData": {
 "results": [
  {
   "GsearchResultClass": "GlocalSearch",
   "listingType": "local",
   "addressLookupResult": "/maps",
   "lat": "33.830296",
   "lng": "-116.545292",
   "accuracy": "4",
   "title": "Palm Springs, CA",
   "titleNoFormatting": "Palm Springs, CA",
   "ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003dPalm+Springs%2C+CA%2C+Palm+Springs%2C+California+%28Palm+Springs%2C+CA%29+%4033.830296%2C-116.545292\u0026saddr",
   "ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003dPalm+Springs%2C+CA%2C+Palm+Springs%2C+California+%28Palm+Springs%2C+CA%29+%4033.830296%2C-116.545292\u0026iwstate1\u003ddir%3Ato",
   "ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003dPalm+Springs%2C+CA%2C+Palm+Springs%2C+California+%28Palm+Springs%2C+CA%29+%4033.830296%2C-116.545292\u0026iwstate1\u003ddir%3Afrom",
   "streetAddress": "Palm Springs, CA",
   "city": "Palm Springs",
   "region": "California",
   "country": "US",
   "staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d33830296\u0026Point.longitude_e6\u003d-116545292\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
   "url": "http://www.google.com/maps?source\u003duds\u0026q\u003dPalm+Springs+CA",
   "postalCode": "",
   "maxAge": 604800,
   "addressLines": [
    "Palm Springs, CA"
   ]
  }
 ],
 "cursor": {
  "moreResultsUrl": "http://www.google.com/local?oe\u003dutf8\u0026ie\u003dutf8\u0026num\u003d4\u0026mrt\u003dyp%2Cloc\u0026sll\u003d37.779160%2C-122.420090\u0026start\u003d0\u0026hl\u003den\u0026q\u003dPalm+Springs+CA"
 },
 "viewport": {
  "center": {
   "lat": "33.830296",
   "lng": "-116.545292"
  },
  "span": {
   "lat": "0.29686",
   "lng": "0.512238"
  },
  "sw": {
   "lat": "33.681866",
   "lng": "-116.801414"
  },
  "ne": {
   "lat": "33.978725",
   "lng": "-116.28918"
  }
 }
}
, "responseDetails": null, "responseStatus": 200}

Using the callback argument

In addition to this response format, the protocol also supports a classic JSON-P style callback which is triggered by specifying a callback argument. When this argument is present, the JSON object is delivered as an argument to the specified callback.

curl -e http://www.my-ajax-site.com \
'http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=Palm%20Springs%20CA&callback=processResults'

This command performs a Local Search that is identical to the previous search, except that it has been altered to pass callback. With this argument in place, instead of a JSON object being returned, a Javascript call is returned in the response and the JSON object is passed via the results parameter.

processResults({"responseData": {
  "results": [
    ...            // results array
   ]
}});

Using the context argument

Finally, the protocol supports a context argument. When both callback and context are specified, the response is encoded as a direct JavaScript call with a signature of: callback(context, results, status, details, unused). Note the slight difference in the following command and response.

curl -e http://www.your-site-here.com \
'http://ajax.googleapis.com/ajax/services/search/local?v=1.0& \
q=Palm%20Springs%20CA&callback=processResults&context=foo'

This command performs a Local Search that is identical to the previous search, except that it has been altered to pass both callback and context. With these arguments in place, instead of a JSON object being returned, a JavaScript call is returned in the response and the JSON object is passed via the results parameter.

processResults('foo',{
 "results": [
   ...          // results array
 ]
});

Code examples

The following sections contain code snippets that show how to access the Local Search API from Flash, Java, PHP, Python, and Perl.

Warning: You need your own API key in order to use the Local Search API. In the example below, replace "INSERT-YOUR-KEY" with your own, unique key. Without a unique key, these examples won't work.

In addition to your API key, you should include the userip parameter, which supplies the IP address of the end-user who made the request and validates that you are not making automated requests in violation of the Terms of Service.

If you have trouble processing the JSON response, visit the JSON.org site, and pay particular attention to the second half of the page where various JSON libraries are referenced. See the JSON reference section below for details on how the Local Search API is made available through the JSON API.

Using Flash

The following code snippet shows how to make a request to the Google Local Search API using Flash. This example uses JSON from the ActionScript 3.0 (AS3) Core Library.

var service:HTTPService = new HTTPService();
service.url = 'http://ajax.googleapis.com/ajax/services/search/local';
service.request.v = '1.0';
service.request.q = 'Palm%20Springs%20CA';
service.request.key = 'INSERT-YOUR-KEY';
service.resultFormat = 'text';
service.addEventListener(ResultEvent.RESULT, onServerResponse);
service.send();

private function onServerResponse(event:ResultEvent):void {
  try {
    var json:Object = JSON.decode(event.result as String);
    // now have some fun with the results...
  } catch(ignored:Error) {
  }
}

Using Java

The following code snippet shows how to make a request to the Google Local Search API using Java. This example uses the JSON library from json.org.

URL url = new URL("http://ajax.googleapis.com/ajax/services/search/local?" +
                  "v=1.0&q=barack%20obama&key=INSERT-YOUR-KEY&userip=INSERT-USER-IP");
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", /* Enter the URL of your site here */);

String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
 builder.append(line);
}

JSONObject json = new JSONObject(builder.toString());
// now have some fun with the results...

Using PHP

The following code snippet shows how to make a request to the Google Local Search API using PHP. This sample assumes PHP 5.2. For older installations of PHP, refer to this comment.

$url = "http://ajax.googleapis.com/ajax/services/search/local?" .
       "v=1.0&q=barack%20obama&key=INSERT-YOUR-KEY&userip=INSERT-USER-IP";

// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, /* Enter the URL of your site here */);
$body = curl_exec($ch);
curl_close($ch);

// now, process the JSON string
$json = json_decode($body);
// now have some fun with the results...

Using Python

The following code snippet shows how to make a request to the Google Local Search API using Python. This sample assumes Python 2.4 or higher. You may need to download and install simplejson.

import urllib2
import simplejson

url = ('http://ajax.googleapis.com/ajax/services/search/local?' +
       'v=1.0&q=barack%20obama&key=INSERT-YOUR-KEY&userip=INSERT-USER-IP')

request = urllib2.Request(url, None, {'Referer': /* Enter the URL of your site here */})
response = urllib2.urlopen(request)

# Process the JSON string.
results = simplejson.load(response)
# now have some fun with the results...

Using Perl

The following code snippet shows how to make a request to the Google Local Search API using Perl. This sample relies on the LWP::UserAgent and JSON modules which you can obtain from CPAN. You may also want to use the URI::Escape module.

#!/usr/bin/perl

my $url = "http://ajax.googleapis.com/ajax/services/search/local?" +
          "v=1.0&q=barack%20obama&key=INSERT-YOUR-KEY&userip=INSERT-USER-IP";

# Load our modules
# Please note that you MUST have LWP::UserAgent and JSON installed to use this
# You can get both from CPAN.
use LWP::UserAgent;
use JSON;

# Initialize the UserAgent object and send the request.
# Notice that referer is set manually to a URL string.
my $ua = LWP::UserAgent->new();
$ua->default_header("HTTP_REFERER" => /* Enter the URL of your site here */);
my $body = $ua->get($url);

# process the json string
my $json = from_json($body->decoded_content);

# have some fun with the results
my $i = 0;
foreach my $result (@{$json->{responseData}->{results}}){
 $i++;
 print $i.". " . $result->{titleNoFormatting} . "(" . $result->{url} . ")\n";
 # etc....
}
if(!$i){
 print "Sorry, but there were no results.\n";
}

JSON reference

Unlike the core JavaScript interface, the JSON interface is exposed through a uniform URL that contains CGI arguments. Your application can use an HTTP stack of its choosing. In order to use the JSON interface:

  • You must construct a properly formatted URL with all necessary CGI arguments.
  • You must send an HTTP referer header that accurately identifies your application.
  • You must process the JSON-encoded response.

Request format

URL base address

The standard URL for the Google Local Search API is:

http://ajax.googleapis.com/ajax/services/search/local

URL arguments

This section describes the arguments that can be used for Local Search requests.

The value of a CGI argument must always be properly escaped. This can be done via the functional equivalent of JavaScript's encodeURIComponent() method.

Required URL arguments

The following table lists the required URL arguments.

Argument

Example

Description

q

q=Palm%20Springs%20CA

This argument supplies the query, or search expression, that is passed into the searcher.

v

v=1.0

This argument supplies protocol version number. The only valid value at this point in time is 1.0.

Optional URL arguments

The following table lists the optional URL arguments.

Argument Example Description

callback

callback=foo

This argument alters the standard response format. When supplied, instead of producing a simple JSON-encoded object, the system produces a JavaScript function call response where the value of callback specifies the name of the function called in the response.

callbackFunction(
  {"responseData" : {
      "results" : [],
      "cursor" : {}
    },
    "responseDetails" : null | string-on-error,
    "responseStatus" : 200 | error-code
});

context

context=bar

This argument is related to the callback argument. When both are supplied, the value of context alters the normal response format associated with callback. The new format is:

callbackFunction(
  contextValue,    // the context arg value
  responseObject,  // the collection of results and cursor
  responseStatus,  // 200 on success, non-200 on failure
  errorDetails)    // error string for non-200 response

hl

hl=fr

This argument supplies the host language of the application making the request. If hl is present in the URL, it will be used. Otherwise, if the Accept-Language HTTP header is present, it will be used. If neither is specified, a value of en is assumed.

key

key=your-key

This argument supplies the application's key. You can sign up for an API key on the Google APIs Console.

If specified, it must be a valid key associated with your site. The key must be validated against the passed referer header. The advantage of supplying a key is so that we can identify and contact you should something go wrong with your application. Without a key, we will still take the same appropriate measures on our side, but we will not be able to contact you. It is definitely best for you to pass a key.

mrt

mrt=kmlonly

This optional argument specifies which type of listing the user is interested in. Valid values include:

  • blended requests KML, Local Business Listings, and Geocode results
  • kmlonly requests KML and Geocode results
  • localonly requests Local Business Listings and Geocode results

If this argument is not supplied, the default value of localonly is used.

rsz

rsz=4

This argument supplies an integer from 1–8 indicating the number of results to return per page.

sll

sll=48.8565,2.3509

This optional argument supplies the search center point for a local search. It's value is a comma separated latitude/longitude pair, e.g., sll=48.8565,2.3509.

sspn

sspn=0.065169,0.194149

This optional argument supplies a bounding box that the local search should be relative to. When using a Google Map, the sspn value can be computed using: myMap.getBounds().toSpan().toUrlValue(); (e.g., sspn=0.065169,0.194149).

start

start=4

This argument supplies the start index of the first search result. Each successful response contains a cursor object (see below) which includes an array of pages. The start property for a page may be used as a valid value for this argument. For reference, a sample cursor object is shown below:

"cursor": {
  "pages": [[
    { "start": "0", "label": 1 },
    { "start": "4", "label": 2 },
    { "start": "8", "label": 3 },
    { "start": "12","label": 4 } ]],
  "estimatedResultCount": "48758",
  "currentPageIndex": 0,
  "moreResultsUrl": "http://www.google.com/search..."
}

userip

userip=192.168.0.1

This argument supplies the IP address of the end-user on whose behalf the request is being made. Requests that include it are less likely to be mistaken for abuse. In choosing to utilize this parameter, please be sure that you're in compliance with any local laws, including any laws relating to disclosure of personal information being sent.

Response format

Basic query

There are two major variations in the response format. When the callback and context arguments are not supplied, the response format is a simple JSON object:

{
  "responseData" : {
    "results" : [],
    "cursor" : {}
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
}

In the JSON fragment above, note that the responseData contains the following properties:

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.

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.

Results array: guaranteed fields

The results array always contains the parameters listed in this section, even if the value is empty.

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 "".

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 "".

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.

The responseStatus property contains a value of 200 on success and a non-200 HTTP error status code on failure. If there is a failure, responseDetails contains a diagnostic string.

Callback argument

Applications can use the callback argument as follows to request a JavaScript callback.

callback({
  "responseData" : {
    "results" : [],
    "cursor" : {}
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
});

Context argument

The context argument must always be specified in conjunction with the callback argument. If the application supplies both callback and context arguments, the response is encoded as a JavaScript procedure call. In this mode of operation:

  • The value of callback becomes the procedure call target.
  • The value of context is passed as the first argument.
  • The value of responseData from above is passed as the second argument.
  • The response status is passed as the third argument.
  • The final argument is either null or a diagnostic string.
processResults(for',{
 "results": [[
  {
   ...
  },
  {
   ...
  },
  ...
 ]],
 "cursor": {
  "pages": [[
   ...
  ]],
  "estimatedResultCount": "n",
  "currentPageIndex": n,
  "moreResultsUrl": "..."
 }
}
, 200 | error-code, null | string-on-error)

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. In Firefox, you can use the JavaScript console or the Firebug. In IE, you can use the Microsoft Script Debugger.
  • If you need to examine the JSON string returned from the server, you can use JSON Lint to make a single, long string human readable.
  • Search the API 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.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.