Drupal 6: Embedding a GMAP view into search results

In this article, I’ll explain one way to embed a GMAP view into your search results.

I downloaded and installed the following modules:

  • content (cck)
  • location_cck
  • gmap
  • gmap_location
  • location
  • location_search
  • views
  • views_ui

Configuring the GMap and Location modules:

  • Location main settings (admin/settings/location), ensure “Enable JIT geocoding” is enabled.
  • Location map links (admin/settings/location/maplinking), ensure “Google Maps” is enabled for Unites States.
  • Location Geocoding options (admin/settings/location/geocoding), enable “Google Maps” for United States.
  • GMap (admin/settings/gmap), enter your Google Maps API key.

I then imported US zip codes into my Drupal database:

$ cd sites/all/modules/contrib/location
$ mysql db_drupal < zipcodes.us.mysql

I created a content type with a single Location CCK field for address. I made this field required and set my desired collection settings. I added some sample nodes, and verified the location coordinates were being added dynamically.

Next I added a new view with the following settings:

  • Name: search_gmap
  • Type: Node
  • Style: GMap; macro: [gmap behavior=+autozoom]; Data source: Location.module;
  • Fields: Node: Title
  • Filters: Node: Published
  • Arguments: Node: Nid; Action to take if argument is not present: display empty text; Enabled: Allow multiple terms per argument.

Last I added some code to my module:

<?php
function MYMODULE_preprocess_search_results(&$vars) {

  // get nodeids from search results
  $node_ids = array();
  foreach ($vars['results'] as $result) {
    if (!is_object($result['node'])) {
      continue;
    }
    $node_ids[] = $result['node']->nid;
  }

  // ensure node ids exist
  if (!count($node_ids)) {
    return;
  }

  // generate views output
  $view_output = views_embed_view('search_gmap', 'default', implode('+', $node_ids));
  if ($view_output) {
    $vars['search_results'] = $view_output . $vars['search_results'];
  }

}
?>

After flushing my caches, and running cron to index my nodes, I ran a search for “nashua”:

GMap search results

Updated: