5.1 Adding a search box that uses the Google geocoder

Often times, you would like to provide an open search box for users to enter a location. This allows users to zoom in to a desired area of interest, and to subsequently access relevant information that you may provide.

Google Maps API provides an easy way to do this through theirĀ google.maps.Geocoder object.

Setting up

Start with a simple maproom layout.

Creating an input text box

Next, create an input text box that will allow users to enter a location. Put this under the H1 tag.

Notice that the “find” button has an onClick event to run the “up206b.geocode()” function that is described below.

Setting up the Google geocoder

In the global space, let’s first declare a variable for the google geocoder and define it as a google maps geocoder object.

Now create a function that will “do” the geocoding, and if successful, will put a marker on the map on the location returned.

Let’s break this down. The geocode function first needs to determine what it is going to geocode. This is handled by telling the function to “grab” whatever value it is that the user entered in the input box, of which we have given the id “address”. jQuery can “grab” the text entered in the input box through this call:

Then, you let Google do the heavly lifting, by supplying their geocoder object with the “address” value.

Finally, you wrap the results around an “if” statement: If successful, then create a marker, if not, alert the user with an error message.

Notice that on success, the Google geocoder returns an array called “results”. You can access the elements of the array as follows:

  • results[0].geometry.location: a google latlng object
  • results[0].geometry.location.lat(): just the latitude value
  • results[0].geometry.location.lng(): just the longitude value
  • results[0].formatted_address: is a string containing the human-readable address of this location. Often this address is equivalent to the “postal address,” which sometimes differs from country to country. (Note that some countries, such as Great Britain, do not allow distribution of true postal addresses due to licensing restrictions.) This address is generally composed of one or more address components. For example, the address “111 8th Avenue, New York, NY” contains separate address components for “111 8th Avenue” (a street address), “New York” (the city) and “NY” (the US state).

You can read more about the Google Geocoder here.
(sample code)

Leave a Reply