You are here

public function IpStack::getCoordinates in Geolocation Field 8.3

Get map location.

Parameters

int $location_option_id: Location option ID.

array $location_option_settings: The current feature settings.

mixed $context: Context like field formatter, field widget or view.

Return value

array With content 'lat' => latitude 'lng' => longitude

Overrides LocationBase::getCoordinates

File

src/Plugin/geolocation/Location/IpStack.php, line 48

Class

IpStack
Fixed coordinates map center.

Namespace

Drupal\geolocation\Plugin\geolocation\Location

Code

public function getCoordinates($center_option_id, array $center_option_settings, $context = NULL) {
  $settings = $this
    ->getSettings($center_option_settings);

  // Access Key is required.
  if (empty($settings['access_key'])) {
    return [];
  }

  // Get client IP.
  $ip = \Drupal::request()
    ->getClientIp();
  if (empty($ip)) {
    return [];
  }

  // Get data from api.ipstack.com.
  $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'],
  ];
}