You are here

public function Nominatim::geocode in Geolocation Field 8.2

Same name and namespace in other branches
  1. 8.3 modules/geolocation_leaflet/src/Plugin/geolocation/Geocoder/Nominatim.php \Drupal\geolocation_leaflet\Plugin\geolocation\Geocoder\Nominatim::geocode()

Geocode an address.

Parameters

string $address: Address to geocode.

Return value

array||null Location or NULL.

Overrides GeocoderBase::geocode

File

modules/geolocation_leaflet/src/Plugin/geolocation/Geocoder/Nominatim.php, line 31

Class

Nominatim
Provides the Nominatim API.

Namespace

Drupal\geolocation_leaflet\Plugin\geolocation\Geocoder

Code

public function geocode($address) {
  if (empty($address)) {
    return FALSE;
  }
  $request_url_base = $this
    ->getRequestUrlBase();
  $url = Url::fromUri($request_url_base . '/search/' . $address, [
    'query' => [
      'email' => $this
        ->getRequestEmail(),
      'limit' => 1,
      'format' => 'json',
      'connect_timeout' => 5,
    ],
  ]);
  try {
    $result = Json::decode(\Drupal::httpClient()
      ->get($url
      ->toString())
      ->getBody());
  } catch (RequestException $e) {
    watchdog_exception('geolocation', $e);
    return FALSE;
  }
  $location = [];
  if (empty($result[0])) {
    return FALSE;
  }
  else {
    $location['location'] = [
      'lat' => $result[0]['lat'],
      'lng' => $result[0]['lon'],
    ];
  }
  if (!empty($result[0]['boundingbox'])) {
    $location['boundary'] = [
      'lat_north_east' => $result[0]['boundingbox'][1],
      'lng_north_east' => $result[0]['boundingbox'][3],
      'lat_south_west' => $result[0]['boundingbox'][0],
      'lng_south_west' => $result[0]['boundingbox'][2],
    ];
  }
  if (!empty($result[0]['display_name'])) {
    $location['address'] = $result[0]['display_name'];
  }
  return $location;
}