hook_geocoder_geocode_values_alter()

If you are using the geocoder module in Drupal 7 and you need the opportunity to alter the data being geocoded right before it gets sent to whichever geocoding service you are using, there is a hook for that. The hook is pretty much undocumented at this time, but it is there. hook_geocoder_geocode_values_alter() is available for you if you need it.

Here is an example use case. Our data had US territories stored in the State field of an address (technically 'administrative_area') However, when you send the query off to geocoder, anything that is a US territory ought to be identified as the country, rather than the state. If you send it as a State, it geocodes incorrectly. So here is an example of a fix using the alter hook.

<?php
/**
 * Implements hook_geocoder_geocode_values_alter().
 */
function MY_MODULE_geocoder_geocode_values_alter(&$source_field_values, &$field_info, &$handler_settings) {
 
// Any item being geocoded that has a state that is actually a
  // territory needs to have its state and country altered to geocode correctly.
 
$territories = array('AS', 'GU', 'FM', 'MH', 'MP', 'PW', 'PR', 'UM', 'VI');
 
// Handle cardinality in case of multiple addresses.
 
foreach ($source_field_values as $key => $value) {
   
$state = (!empty($value['administrative_area'])) ? $value['administrative_area'] : FALSE;
   
// Is there a state, and is it really a territory?
   
if (($state) && (in_array($state, $territories))) {
     
// It is a territory, google geocoder wants it as a country, not a state.
     
$source_field_values[$key]['country'] = $state;
     
// Remove the State entry.
     
unset($source_field_values[$key]['administrative_area']);
    }
  }
}
?>

Incidentally, there are lots of modules with poorly documented alter hooks that may be useful at one time or another. To find them, just search the module code for drupal_alter.

Here is the only other documentation about hook_geocoder_geocode_values_alter. It is the issue and patch that created the alter hook.

modules: