public function Photon::reverseGeocode in Geolocation Field 8.3
Reverse geocode an address.
Intended return subject to available data:
[
'organization' => '',
'address_line1' => '',
'address_line2' => '',
'postal_code' => '',
'sorting_code' => '',
'dependent_locality' => [],
'locality' => [],
'administrative_area' => [],
'country' => [],
'formatted_address' => '',
];
Parameters
float $latitude: Latitude to reverse geocode.
float $longitude: Longitude to reverse geocode.
Return value
array||null Address or NULL.
Overrides GeocoderBase::reverseGeocode
File
- modules/
geolocation_leaflet/ src/ Plugin/ geolocation/ Geocoder/ Photon.php, line 182
Class
- Photon
- Provides the Photon.
Namespace
Drupal\geolocation_leaflet\Plugin\geolocation\GeocoderCode
public function reverseGeocode($latitude, $longitude) {
$url = Url::fromUri($this->requestBaseUrl . '/reverse', [
'query' => [
'lat' => $latitude,
'lon' => $longitude,
'limit' => 20,
],
]);
try {
$result = Json::decode(\Drupal::httpClient()
->get($url
->toString())
->getBody());
} catch (RequestException $e) {
watchdog_exception('geolocation', $e);
return FALSE;
}
if (empty($result['features'][0]['properties'])) {
return FALSE;
}
$countries = \Drupal::service('address.country_repository')
->getList();
$address_atomics = [];
foreach ($result['features'] as $id => $entry) {
if (empty($entry['properties']['osm_type'])) {
continue;
}
switch ($entry['properties']['osm_type']) {
case 'N':
$address_atomics = [
'houseNumber' => !empty($entry['properties']['housenumber']) ? $entry['properties']['housenumber'] : '',
'road' => $entry['properties']['street'],
'city' => $entry['properties']['city'],
'postcode' => $entry['properties']['postcode'],
'state' => $entry['properties']['state'],
'country' => $entry['properties']['country'],
'countryCode' => array_search($entry['properties']['country'], $countries),
];
break 2;
}
}
if (empty($address_atomics)) {
return FALSE;
}
return [
'atomics' => $address_atomics,
'elements' => $this
->addressElements($address_atomics),
'formatted_address' => empty($result['display_name']) ? '' : $result['display_name'],
];
}