Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace Drupal\geocoder_autocomplete;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Component\Utility\Html;
use GuzzleHttp\ClientInterface;
/**
* Defines the GeocoderJsonConsumer service, for return parse GeoJson.
*/
class GeocoderJsonConsumer {
/**
* Drupal http client.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* Language Manager service.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* Service constructor.
*
* @param \GuzzleHttp\ClientInterface $http_client
* The http client.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
*/
public function __construct(
ClientInterface $http_client,
LanguageManagerInterface $language_manager
) {
$this->httpClient = $http_client;
$this->languageManager = $language_manager;
}
/**
* Return json list of geolocation matching $text.
*
* @param string $text
* The text query for search a place.
*
* @return array
* An array of matching location.
*/
public function getAddress($text) {
$language_interface = $this->languageManager->getCurrentLanguage();
$language = isset($language_interface) ? $language_interface->getId() : 'en';
$query = [
'address' => $text,
'language' => $language,
'sensor' => 'false',
];
$uri = 'http://maps.googleapis.com/maps/api/geocode/json';
$response = $this->httpClient->request('GET', $uri, [
'query' => $query,
]);
$matches = array();
if (empty($response->error)) {
$data = json_decode($response->getBody());
if ($data->status == 'OK') {
foreach ($data->results as $result) {
if (!empty($result->formatted_address)) {
$formatted_address = $result->formatted_address;
$matches[] = array(
'value' => Html::escape($formatted_address),
'label' => Html::escape($formatted_address),
);
}
}
}
}
return $matches;
}
}