View source
<?php
declare (strict_types=1);
namespace Drupal\geocoder;
use Drupal\Core\Config\ConfigFactoryInterface;
use Geocoder\Model\AddressCollection;
use Drupal\Core\Extension\ModuleHandlerInterface;
class Geocoder implements GeocoderInterface {
protected $config;
protected $providerPluginManager;
protected $moduleHandler;
public function __construct(ConfigFactoryInterface $config_factory, ProviderPluginManager $provider_plugin_manager, ModuleHandlerInterface $module_handler) {
$this->config = $config_factory
->get('geocoder.settings');
$this->providerPluginManager = $provider_plugin_manager;
$this->moduleHandler = $module_handler;
}
public function geocode(string $address_string, array $providers) {
$this->moduleHandler
->alter('geocode_address_string', $address_string);
foreach ($providers as $provider) {
try {
$result = $provider
->getPlugin()
->geocode($address_string);
if (!isset($result) || $result
->isEmpty()) {
throw new \Exception(sprintf('Unable to geocode "%s" with the %s provider.', $address_string, $provider
->id()));
}
return $result;
} catch (\Exception $e) {
static::log($e
->getMessage());
}
}
return NULL;
}
public function reverse(string $latitude, string $longitude, array $providers) : ?AddressCollection {
$this->moduleHandler
->alter('reverse_geocode_coordinates', $latitude, $longitude);
foreach ($providers as $provider) {
try {
$result = $provider
->getPlugin()
->reverse($latitude, $longitude);
if (!isset($result) || $result
->isEmpty()) {
throw new \Exception(sprintf('Unable to reverse geocode coordinates %s and %s with the %s provider.', $latitude, $longitude, $provider
->id()));
}
return $result;
} catch (\Exception $e) {
static::log($e
->getMessage());
}
}
return NULL;
}
public static function log($message) {
\Drupal::logger('geocoder')
->error($message);
}
}