You are here

geocoder_autocomplete.module in Geocoder autocomplete 7

Same filename and directory in other branches
  1. 8 geocoder_autocomplete.module

@author Stefan Auditor <stefan.auditor@erdfisch.de>

File

geocoder_autocomplete.module
View source
<?php

/**
 * @file
 *
 * @author
 * Stefan Auditor <stefan.auditor@erdfisch.de>
 */

/**
 * Implements hook_permission().
 */
function geocoder_autocomplete_permission() {
  return array(
    'access geocoder autocomplete' => array(
      'title' => t('Access <em>Geocoder Autocomplete</em>'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function geocoder_autocomplete_menu() {
  $items['geocoder/autocomplete'] = array(
    'page callback' => 'geocoder_autocomplete_autocomplete',
    'access arguments' => array(
      'access geocoder autocomplete',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Menu callback.
 */
function geocoder_autocomplete_autocomplete($string = '') {
  $matches = array();
  if ($string !== '') {
    $query = array(
      'address' => $string,
      'language' => $GLOBALS['language']->language,
      'sensor' => 'false',
    );
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?' . drupal_http_build_query($query);
    $response = drupal_http_request($url);
    if (empty($response->error)) {
      $data = json_decode($response->data);
      if ($data->status == 'OK') {
        foreach ($data->results as $result) {
          if (!empty($result->formatted_address)) {
            $matches[$result->formatted_address] = '<div class="reference-autocomplete">' . check_plain($result->formatted_address) . '</div>';
          }
        }
      }
    }
  }
  drupal_json_output($matches);
}

/**
 * Implements hook_field_widget_info().
 */
function geocoder_autocomplete_field_widget_info() {
  return array(
    'geocoder_autocomplete' => array(
      'label' => t('Geocoder text field with autocomplete'),
      'field types' => array(
        'text',
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function geocoder_autocomplete_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => 'textfield',
    '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
    '#size' => 80,
    '#maxlength' => $field['settings']['max_length'],
    '#attributes' => array(
      'class' => array(
        'text-geocoder',
      ),
    ),
  );
  if (user_access('access geocoder autocomplete')) {
    $element['#autocomplete_path'] = 'geocoder/autocomplete';
  }
  return array(
    'value' => $element,
  );
}