You are here

public function Photon::geocode in Geolocation Field 8.3

Same name and namespace in other branches
  1. 8.2 modules/geolocation_leaflet/src/Plugin/geolocation/Geocoder/Photon.php \Drupal\geolocation_leaflet\Plugin\geolocation\Geocoder\Photon::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/Photon.php, line 124

Class

Photon
Provides the Photon.

Namespace

Drupal\geolocation_leaflet\Plugin\geolocation\Geocoder

Code

public function geocode($address) {
  if (empty($address)) {
    return FALSE;
  }
  $options = [
    'q' => $address,
    'limit' => 1,
  ];
  $lang = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  if (in_array($lang, [
    'de',
    'en',
    'it',
    'fr',
  ])) {
    $options['lang'] = $lang;
  }
  $url = Url::fromUri($this->requestBaseUrl . '/api/', [
    'query' => $options,
  ]);
  try {
    $result = Json::decode(\Drupal::httpClient()
      ->get($url
      ->toString())
      ->getBody());
  } catch (RequestException $e) {
    watchdog_exception('geolocation', $e);
    return FALSE;
  }
  $location = [];
  if (empty($result['features'][0])) {
    return FALSE;
  }
  else {
    $location['location'] = [
      'lat' => $result['features'][0]['geometry']['coordinates'][1],
      'lng' => $result['features'][0]['geometry']['coordinates'][0],
    ];
  }
  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;
}