IpStack.php in Geolocation Field 8.3
File
src/Plugin/geolocation/Location/IpStack.php
View source
<?php
namespace Drupal\geolocation\Plugin\geolocation\Location;
use Drupal\geolocation\LocationInterface;
use Drupal\geolocation\LocationBase;
class IpStack extends LocationBase implements LocationInterface {
public static function getDefaultSettings() {
return [
'access_key' => '',
];
}
public function getSettingsForm($option_id = NULL, array $settings = [], $context = NULL) {
$settings = $this
->getSettings($settings);
$form['access_key'] = [
'#type' => 'textfield',
'#title' => $this
->t('Access Key'),
'#default_value' => $settings['access_key'],
'#size' => 60,
'#maxlength' => 128,
];
return $form;
}
public function getCoordinates($center_option_id, array $center_option_settings, $context = NULL) {
$settings = $this
->getSettings($center_option_settings);
if (empty($settings['access_key'])) {
return [];
}
$ip = \Drupal::request()
->getClientIp();
if (empty($ip)) {
return [];
}
$json = file_get_contents("http://api.ipstack.com/" . $ip . "?access_key=" . $settings['access_key']);
if (empty($json)) {
return [];
}
$result = json_decode($json, TRUE);
if (empty($result) || empty($result['latitude']) || empty($result['longitude'])) {
return [];
}
return [
'lat' => (double) $result['latitude'],
'lng' => (double) $result['longitude'],
];
}
}