File Under: APIs, Location

Get Local Search Results From Yahoo

Online maps are a popular way to spice up a site. To get the most use out of them, you need data to plot: addresses from a database, location clicks from the user or at least coordinates for the map’s center. With any map, you have to start somewhere.

If you’re low on data, you can fill in the map with local listings, such as those you’d find in the Yellow Pages. You can show coffee shops or pizza joints right along your other data, or even on its own.

In this tutorial I’ll show how to use Yahoo Local to search for nearby businesses and landmarks, then plot those locations on a Yahoo Map using the Ajax API.

Contents

  1. What You Need
  2. Start With a Basic Map
    1. Add Your App ID
  3. Find Nearby Burritos
    1. Performing the Search
    2. Placing the Markers
  4. Accept User Input
    1. Calling Out The Callbacks
  5. Where to go From Here
    1. Mashup Direction
    2. Academic Direction
    3. Location Direction

What You Need

  • Knowledge of JavaScript, CSS and HTML
  • A Yahoo account and Yahoo Application ID. Yahoo will ask for some information from you, but the good news is you get an ID right away.
  • A little familiarity with Yahoo Maps

Start With a Basic Map

As a starting place for getting Yahoo Local data into your map, we’ll use a basic map from Webmonkey’s introduction to Yahoo Maps. Add this code to a new HTML file:

<!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>My Yahoo Map</title>



		<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=appidhere"></script>

		<script type="text/javascript">

		function initialize_ymap()

		{

			// Create a map object

			var map = new YMap(document.getElementById('ymap'));

			// Display the map centered on a geocoded location

			map.drawZoomAndCenter("San Francisco", 6);

		}

		</script>

		<style>

		div#ymap {

			width: 500px;

			height: 300px;

		}

		</style>



	</head>

	<body onload="initialize_ymap()">

		<h1>My Yahoo Map</h1>

		<div id="ymap"></div>

	</body>



</html>


Add Your App ID

Before you continue to the next section, you need to add your Yahoo Application ID. Find this call to api.maps.yahoo.com and replace appidhere with your own Application ID:

<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=appidhere"></script>




Once you make the change, save the file. Load it in your browser and you should see a map of San Francisco, like this:


Find Nearby Burritos

Now that your map is loading, it’s time to fill it with local goodness. Do you know something else filled with goodness? Burritos. Because I believe in beating bad analogies to death, in this section I’ll show how you can take your blank map tortilla, add some data cheese, then finish off with rice and beans in the form of markers on the map.

Okay, in plain English: I’ll be showing you how to search Yahoo Local, in this case for “burritos,” and plotting the results on our Yahoo Map. Here’s the finished product I’ll show you how to create:


We’ll start with the blank map of San Francisco from the previous section. The first thing we need to do is add a button, which will be used to activate the local search. Place this HTML below the “ymap” div:

	<form>

		<input type="submit" value="Search for burritos" onclick="javascript:doLocalSearch('burritos'); return false;" />

	</form>

Notice that we have a form with a single submit button. When the button is clicked, it calls a JavaScript function doLocalSearch and passes the string ‘burritos’ to it. We’ll need to make that function next.

First a note about the return false line that comes at the end of the bit of JavaScript inside the submit button. That tells the browser not to actually submit the form to the server. JavaScript works in the browser without submitting a form.

Performing the Search

Now that we can call the search with the form button, we need to write the code for the search. Add this function just above the </script> tag near the top of your document:

		function doLocalSearch(keyword)

		{

			map.searchLocal(map.getCenterLatLon(), keyword, 1, 5);

			YEvent.Capture(map, EventsList.onEndLocalSearch, addMarkers);

		}

There are two parts to this new function. The first passes four things off to Yahoo’s searchLocal function:

  1. The center of our map (a YGeoPoint object)
  2. The keyword we’re searching for, burritos
  3. The radius of search results, in miles
  4. The number of search results, 1-20.

Since the search uses Ajax, the results are asynchronous. Unlike many functions that return results immediately, there is a delay for local search. It’s sort of like placing an order at a restaurant. Say you want a burrito, so you let the cashier know. Unless you’re at the airport, you don’t get your burrito right away. Instead, you have to wait for your order to come up. Sometimes you’re even given a number, so you’ll know immediately that your food is ready.

The second line of our new function is where we tell the browser that we care about doing something with the results as soon as they come back. This is often referred to as a callback function. In Yahoo Maps, we enlist the callback function by “capturing” an event with the YEvent.Capture function. In this case, we told the browser to send the results of the search to the addMarkers function.

Placing the Markers

The results of our local search are being sent to the addMarkers function, so we need to create that function. Add this just above the </script> tag near the top of your document (just below the closing curly brace from the previous function):

		function addMarkers(result)

		{

			if (result.Data)

			{

				var places = result.Data.ITEMS;

				for (i=0; i < places.length; i++)

				{

					var thisplace = places[i];

					var marker = new YMarker(new YGeoPoint(thisplace.LATITUDE, thisplace.LONGITUDE));

					marker.addAutoExpand(thisplace.TITLE + '<br />' + thisplace.ADDRESS);

					map.addOverlay(marker);

				}

			}

		}

There are just a few lines in here that do the actual work of adding the marker to the page. The rest ensures that there was data that returned from the search, and iterates through those results.

The places variable is one I created to take the array of results objects from the search. Each object contains the data about the results, such as latitude, longitude, place name (title), and address.

Now that we have received results from a search we hard-coded, let’s look at how we can accept input and let users search our map.

Accept User Input

With the map we created in the previous section, we can search for burritos in San Francisco. What if someone wanted to search for something else somewhere else? Let’s add some ways to accept user input and use it in a local search.

Here’s the example we’ll be working towards:

We can start with the version in the previous section, the static search for burritos. Instead of the single button to start the search, we need a couple input boxes and a new button. In fact, you can scrap the form in the previous section and replace it with this new one:

	<form>

		Search for: <input type="text" name="kw" />

		in <input type="text" name="loc" value="San Francisco, CA" />



		<input type="submit" value="Search Map" onclick="javascript:searchLocation(document.forms[0].loc.value, document.forms[0].kw.value); return false;" />

	</form>

Instead of calling the doLocalSearch function directly, our new button calls searchLocation, a new function we’ll need to create. It passes the two values inside the input boxes to the function, so our new function needs to accept the name of a place and the keyword we’re searching.

Add the searchLocation function to the file, just above the </script> line:

		function searchLocation(placename, keyword)

		{

			map.drawZoomAndCenter(placename, 6);

			YEvent.Capture(map, EventsList.onEndGeoCode, function()

			{

				doLocalSearch(keyword);

			});

		}




Much of the code in this function will look similar to what we wrote in previous sections. We’ve used the drawZoomAndCenter call since the first empty map. Before, we set the map on San Francisco. Now we’re zooming and centering into whatever place the user types in.

YEvent.Capture may also look familiar, from our doLocalSearch function. There we were capturing the onEndLocalSearch event. Here, we need to capture onEndGeoCode event. Why? Because whenever we look up a city (such as with drawZoomAndCenter), Yahoo needs to make an Ajax call to its geocoder. Since the result isn’t available immediately, we need to “place an order” so that something can happen as soon the geocoding is done.

When the geocoding is done, we want to perform the local search. In order to get the keyword passed correctly, we need to wrap the call in an anonymous function. It’s a little confusing if you haven’t seen it before, but that’s a common programming pattern with JavaScript callbacks.


Calling Out The Callbacks

Speaking of callbacks, there are two that go on every time the user searches the map in this example.

Callback one: After calling drawZoomAndCenter, which needs to geocode the location. When this is complete, the first callback initiates the search function.

Callback two: After calling searchLocal, which needs to perform the local search. When this is complete, the second callback plots the markers on the page.

Where to go From Here

You now have the basics down for plotting local data on a Yahoo Map. There are more directions to go than there are results for sushi in San Francisco.

Mashup Direction

What data do you have about your city? In addition to city locations, Yahoo Maps can look up specific addresses and landmarks. Armed with just park names, for example, you could show pet stores near parks.

To see this in action, just return to the search example in the previous section and search for “pet stores” and use “Buena Vista Park San Francisco, CA” as the location.

Academic Direction

Though I was mainly showing you how to use Yahoo Maps local search, you also received an introduction into more advanced JavaScript with callbacks. Now is the time to keep moving forward with your education by testing yourself. Can you edit the static search example to load automatically, eliminating the need for the search button?

Hint: you’ll need to capture an event inside the initialize_maps function.

Location Direction

Use some JavaScript to grab the user’s location as a starting point. Luckily, we have a JavaScript geolocation tutorial. Go for it!