You are here

function location_handler_sort_location_distance::query in Location 7.4

Same name and namespace in other branches
  1. 6.3 handlers/location_handler_sort_location_distance.inc \location_handler_sort_location_distance::query()
  2. 7.5 handlers/location_handler_sort_location_distance.inc \location_handler_sort_location_distance::query()
  3. 7.3 handlers/location_handler_sort_location_distance.inc \location_handler_sort_location_distance::query()

Called to add the sort to a query.

Overrides views_handler_sort::query

File

handlers/location_handler_sort_location_distance.inc, line 118
Coordinates sort handler.

Class

location_handler_sort_location_distance
@file Coordinates sort handler.

Code

function query() {
  $coordinates = location_views_proximity_get_reference_location($this->view, $this->options);
  $this
    ->ensure_my_table();

  // OK, so this part will need a little explanation.
  // Since the distance calculation is so icky, we try quite hard
  // to save some work for the database.
  // If someone has added a field that matches the sort, we just sort on that column!
  $alias = $this->table_alias . '_' . $this->field . '_sort';
  foreach ($this->view->field as $filter) {
    if ($filter->table == 'location' && $filter->field == 'distance' && $filter->options['relationship'] == $this->options['relationship']) {
      if ($filter->options['origin'] == $this->options['origin'] && $filter->options['latitude'] == $this->options['latitude'] && $filter->options['longitude'] == $this->options['longitude']) {

        // We have a match! Sync aliases to make it easier on the database.
        $alias = $filter->field_alias;
      }
    }
  }
  if (empty($coordinates)) {

    // We don't know the distance.
    // Therefore, we don't need to sort on it.
  }
  else {

    // This is done exactly the same as the field version.
    // Views is ok with us redefining the formula for a field.
    // If ANYTHING differs in the configuration, we will use a new alias.
    $this->query
      ->add_orderby(NULL, earth_distance_sql($coordinates['longitude'], $coordinates['latitude'], $this->table_alias), $this->options['order'], $alias);
  }
}