File Under: APIs, Location

Get Local Search Results From Google

Finding what’s nearby is a big part of Google Maps. Now the same information is available on your own site, using Google’s APIs. Let your users search your map, finding nearby restaurants or other businesses and landmarks. Even better, take that data in its raw form and do whatever you want with it.

This tutorial will show several different methods for accessing local data from Google using JavaScript. From plug-and-play maps to direct access to search results, Google is making local listings available to your applications.

Contents

  1. What you’ll need
  2. Plug-and-Play Local Search
    1. Basic Map
    2. Local Search Map Control
    3. More Advanced Plug-and-Play
  3. Access Local Data Directly
    1. Optional Pre-Drawn Results
    2. Load the Local Search API
    3. You Need a Search Controller
    4. Add a Search Complete Callback
  4. Where to go From Here

What you’ll need

  • Knowledge of JavaScript, CSS and HTML
  • A free Ajax Search API key
  • A little familiarity with Google Maps

Plug-and-Play Local Search

Google created some easy ways to add local data into your maps without writing all the code yourself. It’s a one size fits most solution. If you need more control over the data that is returned from Google, you may want to check out the next section. If all you want to do is plot some search results on a map, you’ll be pleased at its simplicity.

Basic Map

For the plug-and-play local search, we’ll start with a basic map similar to the one from Webmonkey’s Introduction to Google Maps.

Here’s what the map looks like:


And the code for making the map display (remember to include your own API code):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

	<head>



		<title>Plug-and-Play Local Search Map</title>

		<script src="http://maps.google.com/maps?file=api&v=2&key=yourkeyhere" type="text/javascript"></script>



		<style type="text/css">



			div#map-canvas {

				width: 500px;

				height: 300px;

			}

		</style>



		<script type="text/javascript">

			var map = null;



			function initialize() {

				if (GBrowserIsCompatible()) {

				  // create a center for our map

				  point = new GLatLng(37.780764,-122.395592)

				  // create a new map.

				  map = new GMap2(document.getElementById("map-canvas"));

				  // set the center

				  map.setCenter(point, 15, G_NORMAL_MAP);

				  // add a zoom control

				  map.addControl(new GSmallZoomControl());



				}

			}

		</script>



	</head>

	<body onload="initialize()" onunload="GUnload()">

		<h1>Plug-and-Play Local Search Map</h1>



		<div id="map-canvas"></div>

	</body>

</html>

Paste the code into a new file, then save and load it in a browser. You should see a zoomed in view of San Francisco streets, just like the map above. Now let’s add in the local search code.

Local Search Map Control

Now that we have a basic map, we need to add the local search control. In terms of JavaScript code, it’s just a single line, though it also requires some imported code and stylesheets.

Below the line where the main JavaScript API is called (right above the style tag), add these two calls to additional Google JavaScript libraries. Again, remember your key for the first one:

	<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=yourkeyhere" type="text/javascript"></script>

	<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script>


Now, inside the style section (right below the style tag), add these two calls to stylesheets:

	    @import url("http://www.google.com/uds/css/gsearch.css");

    	@import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");


The prerequisites completed, it’s finally time for the single line that activates the local search control. Add this code to the initialize function, just below the zoom control line:

		  // add a local search

		  map.addControl(new google.maps.LocalSearch());

Here is our basic map, with the local search control added:


More Advanced Plug-and-Play

Google has another way of adding local search to your map that doesn’t include the control within the map. Again, this is a one size fits most solution, but it solves a common issue: you want your visitors to be able to search the map around one specific location.

With this map, you don’t need to write any code, because Google has a wizard to write the code for you.

Here’s an example Webmonkey created with the wizard:


If you’re looking for an even more advanced, but not plug-and-play, method to use Google’s local search, the next section shows you how to access the data itself.

Access Local Data Directly

In the previous sections you’ve seen how easy it is to incorporate local search results into your Google Map. Chances are if you’re reading this, the plug-and-play version did not fit what you need. In this portion of the tutorial, I’ll show you how to get directly at the local data so you can manipulate it however you need.

Optional Pre-Drawn Results

Google’s local search API does not require a map. Of course, you could use one if you wanted, because you get access to the raw data results. To show off the data, this example will print out the name and address of local results.

Here’s the example I’ll show you how to create:


As you can see, there are two halves to the results. On the left is the code written by Google. Everything comes directly from the JavaScript API and has to be drawn on the screen in order to access the data. On the right is the output from my code, which accesses the data within the results. If you just want access to the data, Google has a little secret: if you make its section disappear with CSS, you’ll still be able to output any data from the results.

Let’s hop into the code and see how you can access Google local results.

Load the Local Search API

This example does not use a map, so the code starts completely anew. Instead of the Maps API, we’ll be using the Ajax Search API. Your API key can remain the same.

Here’s the code you’ll need to set the stage for accessing the search data (remember to include your own key):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <title>My Google AJAX Search API Application</title>

    <script src="http://www.google.com/jsapi?key=yourkeyhere" type="text/javascript"></script>



    <script language="Javascript" type="text/javascript">

    //<![CDATA[

    google.load("search", "1");



    function OnLoad() {

    }

    google.setOnLoadCallback(OnLoad);

    //]]>

    </script>

    <style>

    	.localexample

    	{

    		width: 40%;

    		height: 100%;

    		float: left;

    	}

    	.localexample strong

    	{

    		display: block;

    		border-bottom: 1px dotted #ccc;

    		margin-bottom: 20px;

    	}

    	#googleversion

    	{

    		margin-right: 50px;

    	}

    	#myversion

    	{

    	}

    </style>



  </head>

  <body>

  	<div id="googleversion" class="localexample">

  		<strong>Auto-generated by Google</strong>

	    <div id="searchcontrol" style="">Loading...</div>



	</div>

	<div id="myversion" class="localexample">

		<strong>Created programmatically</strong>

	    <div id="searchresults"></div>

	</div>



  </body>

</html>

If you load this new file into a browser, there won’t be much to see. Let’s add some code to perform a local search.

You Need a Search Controller

The Google Ajax Search API uses what it calls a search controller. Within controllers there are searchers that perform the actual work. The only searcher we’ll use in this section is for local search.

Here’s the JavaScript needed to search for “burritos” in San Francisco. Place the code within the OnLoad function:

      // Create a search control

      var searchControl = new google.search.SearchControl();



      // Add in local search

      var localSearch = new google.search.LocalSearch();

      var options = new google.search.SearcherOptions();

      options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);

      searchControl.addSearcher(localSearch, options);



      // Set the Local Search center point

      localSearch.setCenterPoint("San Francisco, CA");



      // Tell the searcher to draw itself and tell it where to attach

      searchControl.draw(document.getElementById("searchcontrol"));



      // Execute an inital search

      searchControl.execute("burritos");

Save and reload and you’ll see results in the left half of your page. That is because we told Google to “draw” the results inside the element with id=”searchcontrol.”

The Ajax API requires a place to draw the results, the styling is done for you, and you don’t get to choose what data is displayed. You’re reading this part of the tutorial because you do want to access the full data available. Read on to find out how.

Add a Search Complete Callback

Google provides the option of creating a function to receive the data directly. You still need to provide a place for Google to draw the results its own way, though you could make those results disappear with the CSS statement display: none if you only want the data.

To have Google pass the data to our own function, we need to create a callback. In the OnLoad function, right above the execute search call, add this line:

	  // Declare function for using results

	  searchControl.setSearchCompleteCallback(this, gotResults);

We have declared that the gotResults function will be called when the search is complete. Now we have to write the code for gotResults. Paste this outside of the OnLoad function, but still within the <script> tag:

	function gotResults(sc, searcher)

	{

		var resultcontent = '';

		var resultdiv = document.getElementById('searchresults');



		for (i=0; i<searcher.results.length; i++)

		{

			var result = searcher.results[i];

			resultcontent += '<p>'+result.title+'<br />'+result.streetAddress+'</p>';

		}

		resultdiv.innerHTML = resultcontent;

	}



The gotResults function I wrote loops through the results, which are accessible via /searcher.results/. For each individual result, it grabs the /title/ and the /streetAddress/ and output them into the right side of the screen (the element with id=”searchresults”).

Notice that the title contains bold text where search terms are matched. You could use result./titleNoFormatting/ to just get the name of the burrito joint. Phone number, URL, and more are also accessible. Have a look at the GLocalResult properties for a full list.

Where to go From Here

Now you have seen two ways to create a plug-and-play local search map, plus a way to access the data directly. These examples are only the beginning of the cool stuff you can do with Google local search.

Some ideas:

  • Merge the results with a map in your own way. With the raw data you can decide what shows in the infoWindow, or how you want the markers to look.
  • Run multiple searches and compare the results. Are “burritos” closer than “tacos,” or “sushi?” Or, create different markers for each type of results.
  • Start with the user’s location. Our JavaScript geolocation tutorial shows how to grab the user’s location. Set the center of your search to be right where your user is for even better local results.