Features

Features > AJAX

Google’s Mark Lucokvsky shows you how to add search functionality to maps using the GSmapSearchControl Solution

The GSmapSearchControl Solution is a simple to use application of the Google AJAX Search API that is designed to let you easily add a searchable map to your pages, sites and blogs. The rest of this page discusses this topic in detail - but if you just want to cut and paste some code, the “hello world” of the Map Search Control solution is available at the end of this article.

This basic sample demonstrates the following features:

  • A search control that allows you to look up addresses and business listings, plotting the results on a map.
  • The search control has a programmable center point, and at this center point you can specify a custom title and url.
  • The search control takes a small amount of verticle space while inactive, the inactive view is a small map with a white center point.
  • Once a search completes, the map expands and the search result cursors allow you to scroll through the set of search results.
  • Each search result contains a link to a details page for the result as well as a link to get driving directions from the center point of the map to the current search result.
  • The clear button in the center of the cursor controls clears the current set of results and sets the control into the idle state.

The solution is designed for extreme ease of use. As a site designer you are able to control the center point location as well as a custom title and url. In addition, you can easily program a collection of “search links” that you can place on your page that when clicked, will drive the search control.

New Functionality Update

If you are already familiar with this solution, you might find the following new functionality helpful and useful.

Instructions for adding this to your site

Adding the solution is a simple three step process.

Step 1 - Load AJAX Search API, the Google Maps API, and the Map Search Solution

First you need to load the Google AJAX Search API, the Google Maps API, and the Map Search solution into your application. If you don’t already have a Google AJAX Search API key, your first step is to sign up for a key. With your key in hand, add the following five lines of code to your page or blog template.

<!-- maps api, ajax search api, map search solution code -->
<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR-KEY"
    type="text/javascript"></script>

<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=YOUR-KEY"
    type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/mapsearch/gsmapsearch.js"
    type="text/javascript"></script>

<!-- ajax search stylesheet, map search stylesheet -->
<link href="http://www.google.com/uds/css/gsearch.css" rel="stylesheet"
    type="text/css"/>
<link href="http://www.google.com/uds/solutions/mapsearch/gsmapsearch.css"
    rel="stylesheet" type="text/css"/>
      

Step 2 - Define a location on your page for the Map Search Control

The next step is to define a place on your page for the search control (note: you can have more than one). This is typically done by defining a named <div> element as we have shown below:

<div id="mapsearch">Loading...</div>
    

You might want to set some styling attributes on this element to constrain the width of the control, set a border or margin, etc. For example, a style rule like this might be useful.

#mapsearch {
  width : 400px;
  margin : 10px;
  padding : 4px;
  border : 1px solid #f9f9f9;
}
    

In addition to this base style, the height of the idle state map and the active state map is easily modified.

/* set height of idle state map */
#mapsearch .gsmsc-idleMapDiv { height : 200px; }

/* set height of active state map */
#mapsearch .gsmsc-mapDiv { height : 300px; }
    
Step 3 - Create a GSmapSearchControl and bind it to your page

The final step involves creating and configuring the control. The control is very powerful and offers several options. In this section, we will describe the simplest case of adding a control to your page or blog followed several examples that demonstrate more advanced concepts.

The first step is to actually get your code to run. The easiest way to do this is to either extend an existing body onload handler, or create a new one. Find the <body> element on your page and add an onload handler.

<body onload="OnLoad()">
    

Now write your onload handler by adding some code to an existing <script> block, or by creating a new one. Find the <body> element on your page and add an onload handler. The code snippet below demonstrates how to create a new map search control that will appear on your page inside the element named “mapsearch”. The map will center itself on Google corporate headquarters located at “1600 Amphitheatre Parkway, Mountain View, CA.”

<script type="text/javascript">
function OnLoad() {
  new GSmapSearchControl(
        document.getElementById("mapsearch"),             // container
        "1600 Amphitheatre Parkway, Mountain View, CA",   // center point
        null                                              // options
        );
}
</script>
    

Options

Notice in the above example, the value null is passed as the options argument, a Javascript object which is typically specified in object literal form. The following sections describe the possible values for options. These values support the following features:

  • Setting a special title and url for the map center point.
  • Specifying a set of hot spots on your page that will trigger searches
Setting a special title and url for the map center point

A special title and url can be programmed into the control and bound to the white center point marker of an active map. A typical use case for this feature might be to specify a conference name and conference url, or a company name and url. In order to request this functionality, the title and url properties of the options argument must be set. The following code snippet demonstrates this.

<script type="text/javascript">
function OnLoad() {

  // set title to the Googleplex and the link to
  // the Google corporate information page
  var options =
    {
      title : "Googleplex",
      url : "http://www.google.com/corporate/index.html"
    }

  // create the map search control
  new GSmapSearchControl(
        document.getElementById("mapsearch"),
        "1600 Amphitheatre Parkway, Mountain View, CA",
        options
        );
}
</script>
    
Setting up hot spots

A common use case for this control is program hot spots on to your page thatwhen clicked will drive the search control. These hot spots might take the form of a list of recommendations, hotels, restaurants, etc. The search control supports this by allowing you to program a list of HTML elements and associated queries. When your users click on the element, the search control is activated with the specified query.

The options argument contains an optional hotspot property. This property is an array of objects, where each object contains an element property which is a reference to an HTML element on your page, as well as a query property which specifies a query to execute when the element is clicked.

The following code fragment demonstrates the use of this feature including the CSS declarations,HTML fragments, and options programming. If you prefer programming this on your own, perhaps by using <a> tags with javascript: urls, that’s a perfectly reasonable way to proceed. We include this capability in the solution because for some of our users, this is a simpler mechanism that requires less of their time to develop. In the snippet that follows we are going to show sample CSS, HTML, and search control initialization logic.

/* define the CSS used to style the hotspots */
h4.hotspot {
  font-size : 100%;
  font-weight : normal;
  color : rgb(9, 122, 182);
  margin-left : 8px;
  margin-top : 0px;
  margin-bottom : 2px;
  font-style : normal;
  cursor : pointer;
}

h4.hotspot:hover {
  color : rgb(237, 92, 11);
  text-decoration : underline;
}

<!--
Define the HTML that places the hotspots on your page.
Note, you can use any HTML element you like including li, div, etc.
-->

<div id="mapsearch">Loading...</div>
<h3 class="hotspotheader">Recommendations</h3>
<h4 id="hs01" class="hotspot">Caffeine</h4>
<h4 id="hs02" class="hotspot">Thai Food</h4>
<h4 id="hs03" class="hotspot">Pizza</h4>

<h4 id="hs04" class="hotspot">Gym</h4>
<h4 id="hs05" class="hotspot">Hotel Avante</h4>
<h4 id="hs06" class="hotspot">Residence Inn</h4>
<h4 id="hs07" class="hotspot">The Four Seasons</h4>
<h4 id="hs08" class="hotspot">The Westin, Palo Alto</h4>

<script type="text/javascript">
function OnLoad() {

  // Create an array of hotspots. Each entry contains and html element
  // from your page, and the query to execute when that element is clicked
  var hotspotsList = [
      { element : document.getElementById("hs01"), query : "Starbucks" },
      { element : document.getElementById("hs02"), query : "Amarin Thai" },
      { element : document.getElementById("hs03"), query : "Frankie Johnnie & Luigi" },
      { element : document.getElementById("hs04"), query : "Hotel Avante" },
      { element : document.getElementById("hs05"), query : "Residence Inn" },
      { element : document.getElementById("hs06"), query : "Four Seasons Palo Alto" },
      { element : document.getElementById("hs07"), query : "Westin Palo Alto" }
  ];

  // set title to the Googleplex and the link to
  // the Google corporate information page
  // set the hotspot list to the list above
  var options =
    { title : "Googleplex",
      url : "http://www.google.com/corporate/index.html",
      hotspots : hotspotsList
    }

  // create the map search control
  new GSmapSearchControl(
        document.getElementById("mapsearch"),
        "1600 Amphitheatre Parkway, Mountain View, CA",
        options
        );
}
</script>
    
New! Setting Custom Center Icon

Applications can either accept the default center location icon, or they can supply their own GIcon and the system will use that Icon to mark the center point of the map.

The options argument contains an optional centerIcon property. When supplied, property must specify a valid GIcon. When specified, this icon is used as the center point marker for both the idle and active map.

The following code fragment demonstrates the use of this feature. It demonstrates the use of both a hand built icon, as well as the G_DEFAULT_ICON two calls:

// use the ridefinder, small yellow icon as the center point marker
var ci = new GIcon();
ci.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
... (rest of initialization omitted)

new GSmapSearchControl(container,
                       "1600 Amphitheatre Parkway, Mountain View, CA",
                       { title : "Googleplex",
                         url : "http://www.google.com/press/factorytour.html",
                         centerIcon : ci
                       }
                       );

// use the G_DEFAULT_ICON as the center point marker
new GSmapSearchControl(container,
                       "1600 Amphitheatre Parkway, Mountain View, CA",
                       { title : "Googleplex",
                         url : "http://www.google.com/press/factorytour.html",
                         centerIcon : G_DEFAULT_ICON
                       }
                       );
    
New! Setting Custom Selected and Unselected Icons

Applications are able to specify the icons for the currently selected search result as well as for all unselected search results using a similar model.

The options argument contains an optional selectedIcon property. When supplied, property must specify a valid GIcon. When specified, this icon is used as the marker for the selected search result.

The options argument contains an optional unselectedIcon property. When supplied, property must specify a valid GIcon. When specified, this icon is used as the marker for all other search results.

The following code fragment demonstrates the use of this feature:

// use the G_DEFAULT_ICON as the for selected and unselected search results
new GSmapSearchControl(container,
                       "1600 Amphitheatre Parkway, Mountain View, CA",
                       { title : "Googleplex",
                         url : "http://www.google.com/press/factorytour.html",
                         selectedIcon : G_DEFAULT_ICON,
                         unselectedIcon : G_DEFAULT_ICON
                       }
                       );
    
Controlling the Zoom Level

Applications can control the Zoom Level for the idle map (displayed when no searches are active) as well as for the active map (displayed when a map is showing results). The system defines two constants that are helpful when configuring this aspect of the control:

  • GSmapSearchControl.IDLE_MAP_ZOOM - the default zoom level for the idle map
  • GSmapSearchControl.ACTIVE_MAP_ZOOM - the default zoom level for the active map

The options argument contains an optional idleMapZoom property. When supplied, this property specifies the zoom level for the idle map. A common use of this property is to have the idle map’s zoom level match the default zoom level for the active map. In order to do this, use the constants described above to set idleMapZoom to GSmapSearchControl.ACTIVE_MAP_ZOOM.

The zoom level for the active map is controlled in a similar manner. The options argument contains an optional activeMapZoom property. When supplied, this property specifies the zoom level for the active map. Note: Applications can use these properties independently of each other.

The following code fragment demonstrates the use of this feature.

// set the idle map zoom so that it matches the
// default active map zoom level
new GSmapSearchControl(container,
                       "1600 Amphitheatre Parkway, Mountain View, CA",
                       { title : "Googleplex",
                         url : "http://www.google.com/press/factorytour.html",
                         idleMapZoom : GSmapSearchControl.ACTIVE_MAP_ZOOM
                       }
                       );

// set the active map zoom level up by 1
new GSmapSearchControl(container,
                       "1600 Amphitheatre Parkway, Mountain View, CA",
                       { title : "Googleplex",
                         url : "http://www.google.com/press/factorytour.html",
                         activeMapZoom : GSmapSearchControl.ACTIVE_MAP_ZOOM+1
                       }
                       );
    
New! Enabling the Map Type Control

The default behavior of the maps created by this control is for them to not contain the GMapTypeControl, the control that allows switching between map, hybrid and satellite mode. This behavior is programmable allowing applications to cause the control to build maps with the GMapTypeControl available on all maps, or just on the active map.

The options argument contains an optional mapTypeControl property. When supplied, this property specifies which maps should be programmed to include the GMapTypeControl.

  • GSmapSearchControl.MAP_TYPE_ENABLE_ACTIVE - When this value is specified for the mapTypeControlproperty, the active map will contain a GMapTypeControl
  • GSmapSearchControl.MAP_TYPE_ENABLE_ALL - When this value is specified for the mapTypeControl property, both the active map and the idle map will contain a GMapTypeControl

The following code fragment demonstrates the use of this feature.

// enable a GMapTypeControl on the active map
new GSmapSearchControl(container,
                       "1600 Amphitheatre Parkway, Mountain View, CA",
                       { title : "Googleplex",
                         url : "http://www.google.com/press/factorytour.html",
                         mapTypeControl : GSmapSearchControl.MAP_TYPE_ENABLE_ACTIVE
                       }
                       );

// enable a GMapTypeControl on the all maps
new GSmapSearchControl(container,
                       "1600 Amphitheatre Parkway, Mountain View, CA",
                       { title : "Googleplex",
                         url : "http://www.google.com/press/factorytour.html",
                         mapTypeControl : GSmapSearchControl.MAP_TYPE_ENABLE_ALL
                       }
                       );

The “Hello World” of GSmapSearchControl

The following page demonstrates a complete page which uses the GSmapSearchControl solution. You can start with this simple page, change internal to the value of your key and be up and running in seconds.

<html>
<head>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>GSmapSearchControl Sample</title>

  <!-- Note:
    Make sure to replace the &key=internal with &key=YOUR-KEY
    in both the maps API script load and in the Ajax Search API script load statements
  -->
  <!-- maps api, ajax search api, map search solution code -->

  <script src="http://maps.google.com/maps?file=api&v=2&key=internal"
    type="text/javascript"></script>
  <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=internal"
    type="text/javascript"></script>
  <script src="http://www.google.com/uds/solutions/mapsearch/gsmapsearch.js"
    type="text/javascript"></script>

  <!-- ajax search stylesheet, map search stylesheet -->
  <link href="http://www.google.com/uds/css/gsearch.css" rel="stylesheet"
    type="text/css"/>
  <link href="http://www.google.com/uds/solutions/mapsearch/gsmapsearch.css"
    rel="stylesheet" type="text/css"/>
  <style type="text/css">
    body, table, p{
      background-color: white;
      font-family: Arial, sans-serif;
      font-size: 13px;
    }

    #mapsearch {
      width : 400px;
      margin-left: 10px;
      padding: 4px;
      border : 1px solid #f9f9f9;
    }
  </style>
  <script type="text/javascript">

    function OnLoad() {

      var options = {
            title : "Googleplex",
            url : "http://www.google.com/corporate/index.html"
            }

      new GSmapSearchControl(
            document.getElementById("mapsearch"),
            "1600 Amphitheatre Parkway, Mountain View, CA",
            options
            );
    }
  </script>
</head>
<body onload="OnLoad()">
  <div id="mapsearch">Loading...</div>
</body>
</html>

Examples

digg.com logo Like this article? Digg it!

The Future of Web Design is back in New York, 3-4 Nov, bringing you our fresh blend of amazing speakers, great advice and tons of networking potential. Use our special code FOWD/Vitamin to get a 15% discount!

32 Responses to “Create a searchable Google map”

  1. mapperz says

    Nice Clean examples with good advice.

    works fine in blogger. just a few issues with blogger beta.

    mapperz

  2. BillyG says

    Unbelievable,

    Just today, I decided to move my list of links into their respective info balloons.

    And so fast!

    Thanks bud.

  3. Skylog » Blog Archive » links for 2006-10-31 says

    […] Create a searchable Google map (tags: javascript) […]

  4. Spot Gratis says

    Pubblica la tua attività su mappa gratis
    SPOT GRATIS

  5. Prashant says

    Wow, this is a very useful article!

    Thanks a lot.

  6. Vitamin Features » Create a searchable Google map - Matt Heerema : Web Design says

    […] Create a searchable Google map. […]

  7. Naren says

    Same information in google api page is available in this page…

    Why this page could not contain some more examples and informations !!!.

  8. Reality Me » links for 2006-10-31 says

    […] Vitamin Features » Create a searchable Google map (tags: google googlemaps ajax maps api development JavaScript) […]

  9. goudaille » Blog Archive » links for 2006-11-01 says

    […] Vitamin Features » Create a searchable Google map Créer facilement une carte Google Maps: à ajouter à Cent Papiers. (tags: sig googlemaps) […]

  10. Blogging Web 2.0 Web Design | Social Networking | Color Tagging | Ajax | CSS | SEO | Tyic » Create a searchable Google map says

    […] http://www.thinkvitamin.com/features/ajax/create-a-searchable-google-map […]

  11. links for 2006-11-01 « Donghai Ma says

    […] Vitamin Features » Create a searchable Google map (tags: google programming tips tutorial web javascript ajax) […]

  12. links for 2006-11-01 « I do says

    […] Vitamin Features » Create a searchable Google map (tags: googlemaps search mapping map) […]

  13. Patrick says

    Great article, Marc. Thank you very much for writing it. I was able to follow your steps with great ease and am using your example to make up a searchable map of Austin (Texas). The preset hotspots idea… that’s got amazing potential.

  14. Web Design Victoria BC - Blog says

    Create a searchable Google map…

    Google’s Mark Lucokvsky shows you how to add search functionality to maps using the GSmapSearchControl Solution.

    ……

  15. joe says

    Almost all this information is on the google website

  16. Breaking the post drought at Matt Didcoe says

    […] And another link, more interesting to people working with Google Maps: http://www.thinkvitamin.com/features/ajax/create-a-searchable-google-map […]

  17. Derek DeMarco says

    I had way too much fun doing this over the weekend. the process is well described and I have put it to use. Thanks

  18. Tony Montana says

    Hi, thanks for the article, though I cant figure out how to resize the map, “make it stretch across the whole page” Could someone show me how to do this? (I made it 100% width, but I cant get the height to work. This is the page I made: http://www.nqccs.com.au/vitamin2.htm

  19. eliphas says

    I don’t see the point of this article I am sorry.
    I can read the same infomration on the google api search page, why making a doublon of it. feeed us with more ideas please.

  20. perryboy.com » Blog Archive » Daily Links says

    […] Vitamin Features » Create a searchable Google map (tags: google ajax googlemaps) […]

  21. sanewebdirectory says

    WoW! This is good article which describes to implement Searchable Google Map in your website.

  22. urlwebdirectory says

    Thanks for writing this article. It was easy to follow the steps easily and I will be using this example in our next project to make a searchable map.

  23. Chris Huang says

    This is great! ONLY!!! It doesn’t work with IE 6.

    IE will refuse to read Element as an object, cause javascript to fail.

  24. All in a days work… says

    […] Create a searchable Google map add search functionality to maps using the GSmapSearchControl […]

  25. ANTONY says

    Thank’s for this post… Very helpfull…
    Antony

  26. google reklam says

    good luck

  27. nakliyat says

    THANKS

  28. gazeteler says

    thanks

  29. mikehedge.com » Blog Archive » stuff says

    […] http://www.thinkvitamin.com/features/ajax/create-a-searchable-google-map […]

  30. Avasilcai Daniel says

    Oh, this is really useful. i need a map like this, hope it will be across browsers.

  31. Recursos y Tutoriales » Blog Archive » Crear un Google maps search solutions says

    […] The GSmapSearchControl Solution is a simple to use application of the Google AJAX Search API that is designed to let you easily add a searchable map to your pages, sites and blogs. The rest of this page discusses this topic in detail - but if you just want to cut and paste some code, the “hello world” of the Map Search Control solution is available at the end of this article. […]

  32. IVR says

    A new way, I have to say!

Leave a Reply

Basic HTML (<strong>, <em>, <a>, etc.) is allowed in your comments. Please be respectful and keep your comments on-topic. If we think you're being offensive for no reason, we'll delete your comment.

Comments RSS