You are here

function google_geocode_location in Location 7.5

Same name and namespace in other branches
  1. 5.3 geocoding/google.inc \google_geocode_location()
  2. 5 geocoding/google.inc \google_geocode_location()
  3. 6.3 geocoding/google.inc \google_geocode_location()
  4. 7.3 geocoding/google.inc \google_geocode_location()
  5. 7.4 geocoding/google.inc \google_geocode_location()

Perform a geocode on a location array.

Parameters

$location: The location array to process.

Return value

an associative array with keys 'lat' and 'lon' containing the coordinates.

File

geocoding/google.inc, line 112
Google geocoder.

Code

function google_geocode_location($location = array()) {
  $delay_trigger =& drupal_static(__FUNCTION__);
  $delay = variable_get('location_geocode_google_delay', 0);
  if ($delay > 0 && $delay_trigger) {
    usleep($delay * 1000);
  }
  if (function_exists('gmap_get_key')) {
    $key = gmap_get_key();
  }
  else {
    $key = variable_get('location_geocode_google_apikey', '');
  }
  $query = array(
    'key' => $key,
    'sensor' => 'false',
    // Required by TOS.
    'output' => 'xml',
    //'ll' => 0,

    //'spn' => 0,
    'gl' => $location['country'],
    'q' => _google_geocode_flatten($location),
  );
  $url = url('http://maps.google.com/maps/geo', array(
    'query' => $query,
    'external' => TRUE,
  ));
  $http_reply = drupal_http_request($url);
  $delay_trigger = TRUE;
  $status_code_match = array();
  preg_match('/<code>(.*)<\\/code>/', $http_reply->data, $status_code_match);
  $status_code = $status_code_match[1];
  if ($status_code != 200) {
    watchdog('location', 'Google geocoding returned status code: %status_code', array(
      '%status_code' => $status_code,
    ));
    return NULL;
  }
  $accuracy_code_match = array();
  preg_match('/Accuracy="([0-9])"/', $http_reply->data, $accuracy_code_match);
  $accuracy_code = $accuracy_code_match[1];
  $min_accuracy = variable_get('location_geocode_' . $location['country'] . 'google_accuracy_code', variable_get('location_geocode_google_minimum_accuracy', '3'));
  if ($accuracy_code < $min_accuracy) {
    watchdog('location', 'Google geocoding result for %country did not meet the minimum accuracy level of %min_accuracy. Result accuracy: %accuracy_code', array(
      '%country' => $location['country'],
      '%min_accuracy' => $min_accuracy,
      '%accuracy_code' => $accuracy_code,
    ));
    return NULL;
  }
  $latlon_match = array();
  preg_match('/<coordinates>(.*)<\\/coordinates>/', $http_reply->data, $latlon_match);
  $latlon_exploded = explode(',', $latlon_match[1]);
  return array(
    'lat' => $latlon_exploded[1],
    'lon' => $latlon_exploded[0],
  );
}