You are here

public function views_plugin_style_geojson::render in Views GeoJSON 7

Same name and namespace in other branches
  1. 6 views/views_plugin_style_geojson.inc \views_plugin_style_geojson::render()

Implementation of view_style_plugin::render().

Overrides views_plugin_style::render

File

views/views_plugin_style_geojson.inc, line 336
Views style plugin to render nodes in the GeoJSON format.

Class

views_plugin_style_geojson
Implementation of views_plugin_style.

Code

public function render() {
  $args = func_get_args();
  $results = array_shift($args);
  $features = array(
    'type' => 'FeatureCollection',
    'features' => array(),
  );

  // Render each row.
  foreach ($results as $i => $row) {
    $this->view->row_index = $i;
    if ($feature = _views_geojson_render_fields($this->view, $row, $i)) {
      $features['features'][] = $feature;
    }
  }
  unset($this->view->row_index);

  // Render the collection to JSON.
  $json = drupal_json_encode($features);
  if (!empty($this->options['jsonp_prefix'])) {
    $json = $this->options['jsonp_prefix'] . "({$json})";
  }

  // Replace form field placeholders.
  $json = $this
    ->form_fields_replace($json);
  if (!empty($this->view->preview)) {

    // Pretty-print the JSON. This only works for 'page' displays.
    $json = _views_geojson_encode_formatted($features);
    if (!empty($this->options['jsonp_prefix'])) {
      $json = $this->options['jsonp_prefix'] . "({$json})";
    }
    if ($this->display->display_plugin === 'page') {
      $json = "<pre>{$json}</pre>";
    }

    // Replace form field placeholders.
    $json = $this
      ->form_fields_replace($json, FALSE);
  }
  elseif ($this->display->display_plugin === 'feed') {
    $content_type = $this->options['content_type'] === 'default' ? 'application/json' : $this->options['content_type'];
    drupal_add_http_header('Content-Type', "{$content_type}; charset=utf-8");
  }
  else {
    if ($this->display->display_plugin === 'page' && !$this->options['using_views_api_mode']) {

      // Change the content type header since we're sending a JSON response.
      $content_type = $this->options['content_type'] === 'default' ? 'application/json' : $this->options['content_type'];
      drupal_add_http_header('Content-Type', "{$content_type}; charset=utf-8");

      // Page display prints and exits; this is BAD (prevents caching) but
      // supports legacy configurations.
      print $json;
      drupal_exit();
    }
  }

  // Everything else returns output.
  return $json;
}