clean install

This commit is contained in:
2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 changed files with 3555714 additions and 0 deletions

51
web/modules/views_geojson/.gitignore vendored Normal file
View File

@@ -0,0 +1,51 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,104 @@
CONTENTS OF THIS FILE
---------------------
* Summary
* Requirements
* Installation
* Usage
* Bounding Box Support
* To Do
* Credits
* Current Maintainers
SUMMARY
-------
Views GeoJSON is a style plugin for Views to deliver location-specific data in GeoJSON format, (see GeoJSON spec: http://geojson.org/geojson-spec.html).
Each row is output as a GeoJSON "Features" including geospatial data and optional metadata. All features are wrapped in a "Feature Collection" object.
REQUIREMENTS
------------
Drupal modules:
* Views
* Serialization
* Rest
Optional Drupal modules:
* Geofield 8.x-1.0-alpha2 or greater
INSTALLATION
------------
Install the module as usual.
See https://www.drupal.org/node/1897420 for help installing Drupal 8 modules.
USAGE
-----
1. Create a View with a Feed display on content with geospatial data.
2. Add fields to output a Geofield, longitude & latitude or WKT.
3. Optionally add fields for name and description.
4. Set Format for the display to "GeoJSON Feed".
5. In the "Style options" for this format:
* Choose Map Data Source (Other: Lat/Lon Point, Geofield, etc.)
* Assign the fields that represent Latitude and Longitude.
* Optionally choose fields representing name and description for each point.
* Optionally set a JSONP prefix, (see http://en.wikipedia.org/wiki/JSONP).
* Set the Content-type header to be sent. The default is "application/json",
the standard MIME type for JSON, per http://www.ietf.org/rfc/rfc4627.txt.
6. If using with the OpenLayers module, your new GeoJSON layer will be available
as an Overlay layer on the "Layers & Styles" tab when editing your map.
Bounding Box Filtering
--------------------
GeoJSON views can accept a bounding box as an argument to return only the
points within that box.
It has been tested with OpenLayers' Bounding Box Strategy but should work
with any mapping tool that requests bounding box coordinates as
"?bbox=left,bottom,right,top" in the query string. Argument ID "bbox" is
default for OpenLayers but can be changed.
OpenLayers 7.x-2.x-dev is currently required for OpenLayers BBOX integration.
See OpenLayers issue http://drupal.org/node/1493344, "Support BBOX strategy in
the GeoJSON layer type".
1. Create a GeoJSON view as above in USAGE.
2. Add a layer to OpenLayers of type GeoJSON, at
admin/structure/openlayers/layers/add/openlayers_layer_type_geojson,
specifying the URL to your GeoJSON feed and checking the box for "Use
Bounding Box Strategy".
3. In your GeoJSON View configuration, add a Contextual Filter of type:
"Custom: Bounding box".
4. In the Contextual Filter settings, under "When the filter value is NOT in
the URL as a normal Drupal argument", choose: "Provide default value".
5. In the "Type" dropdown, choose: "Bounding box from query string".
6. For OpenLayers, leave "Query argument ID" as "bbox" and click Apply.
TO DO
-----
* Support addditional GeoJSON feature types like LineString.
* Support an optional altitude coordinate for Point positions.
* Support additional coordinate systems.
CREDITS
-------
This module was originally born from a patch by tmcw to the OpenLayers module
(http://drupal.org/node/889190#comment-3376628) and adapted to model the Views
Datasource module (http://drupal.org/project/views_datasource).
Much of the code is drawn directly from these sources.
CURRENT MAINTAINERS
-------------------
* jeffschuler - http://drupal.org/user/239714

View File

@@ -0,0 +1,24 @@
{
"name": "drupal/views_geojson",
"type": "drupal-module",
"description": "Provides a Views feed style for GeoJSON output",
"keywords": [
"views",
"geojson"
],
"homepage": "https://www.drupal.org/project/views_geojson",
"license": "GPL-2.0-or-later",
"require": {
"php": ">= 7",
"drupal/core": "^8.0 || ^9.0 || ^10.0",
"itamair/geophp": "^1.3"
},
"require-dev": {
"drupol/drupal-conventions": "^1.7"
},
"support": {
"issues": "https://www.drupal.org/project/issues/views_geojson",
"irc": "irc://irc.freenode.org/drupal-contribute",
"source": "http://git.drupal.org/project/views_geojson.git"
}
}

View File

@@ -0,0 +1,39 @@
views.display.geojson_export:
type: views_display_path
label: 'GeoJSON export display options'
views.style.geojson:
type: views_style
label: 'GeoJSON output format'
mapping:
data_source:
type: mapping
label: 'Data Source'
mapping:
value:
type: string
label: 'Map Data Sources'
latitude:
type: string
label: 'Latitude Field'
longitude:
type: string
label: 'Longitude Field'
geofield:
type: string
label: 'Geofield'
geolocation:
type: string
label: 'Geolocation'
wkt:
type: string
label: 'WKT'
name_field:
type: string
label: 'Title Field'
description_field:
type: string
label: 'Description'
jsonp_prefix:
type: string
label: 'JSONP prefix'

View File

@@ -0,0 +1,151 @@
<?php
namespace Drupal\views_geojson\Plugin\views\argument;
use Drupal\views\Plugin\views\join\JoinPluginBase;
use Drupal\views\Plugin\views\argument\StringArgument;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Argument handler for Bounding Boxes.
*
* @ingroup views_argument_handlers
*
* @ViewsArgument("views_geojson_bbox_argument")
*/
class BBoxArgument extends StringArgument implements ContainerFactoryPluginInterface {
/**
* @TODO: Is this correct?
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['round_coordinates'] = ['default' => TRUE];
return $options;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition
);
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
unset($form['case']);
unset($form['path_case']);
$form['description']['#markup'] .= $this->t('<br><strong>The format should be: <em>"left,bottom,right,top"</em></strong>.');
$form['round_coordinates'] = [
'#type' => 'checkbox',
'#title' => $this->t('Round coordinates'),
'#default_value' => $this->options['title'],
'#description' => $this->t('Round coordinates to two decimal places. This can help in caching bounding box queries. For instance, "-0.542,51.344,-0.367,51.368" and "-0.541,51.343,-0.368,51.369" would use the same SQL query.'),
];
}
/**
* {@inheritdoc}
*
* If we've been passed a bounding box, it's parsable, and the view style
* has a geofield, then we work out which fields to add to the query and add a
* where clause.
*/
public function query($group_by = FALSE) {
if ($bbox = $this->getParsedBoundingBox()) {
$geojson_options = $this->view->getStyle()->options;
$geofield_type = NULL;
$geofield_name = NULL;
if (!empty($geojson_options['data_source']['value'])) {
$geofield_type = $geojson_options['data_source']['value'];
if (!empty($geojson_options['data_source'][$geofield_type])) {
$geofield_name = $geojson_options['data_source'][$geofield_type];
}
}
if (empty($geofield_type) || empty($geofield_name)) {
return;
}
// @todo - get geo_table from field definition?
$geo_table = "node__{$geofield_name}";
if ($geofield_type == 'geolocation') {
$geo_table_entity_id_field = 'entity_id';
$field_lat = "{$geo_table}.field_geolocation_lat";
$field_lng = "{$geo_table}.field_geolocation_lng";
}
elseif ($geofield_type == 'geofield') {
$geo_table_entity_id_field = 'entity_id';
$field_lat = "{$geo_table}.{$geofield_name}_lat";
$field_lng = "{$geo_table}.{$geofield_name}_lon";
}
if (!empty($geo_table)) {
$this->query->ensureTable($geo_table, NULL, new JoinPluginBase([
'table' => $geo_table,
'field' => $geo_table_entity_id_field,
'left_table' => 'node_field_data',
'left_field' => 'nid',
],
NULL, NULL));
}
$this->query->addWhere('bbox', $field_lat, $bbox['bottom'], '>=');
$this->query->addWhere('bbox', $field_lat, $bbox['top'], '<=');
$this->query->addWhere('bbox', $field_lng, $bbox['left'], '>=');
$this->query->addWhere('bbox', $field_lng, $bbox['right'], '<=');
}
}
/**
* Parses the bounding box argument.
*
* Parses the bounding box argument. Returns an array keyed 'top', 'left',
* 'bottom', 'right' or FALSE if the argument was not parsed succesfully.
*
* @return array|bool
* The calculated values.
*/
public function getParsedBoundingBox() {
static $values;
if (!isset($values)) {
$exploded_values = explode(',', $this->getValue());
if (count($exploded_values) == 4) {
$values['left'] = (float) $exploded_values[0];
$values['bottom'] = (float) $exploded_values[1];
$values['right'] = (float) $exploded_values[2];
$values['top'] = (float) $exploded_values[3];
if ($this->options['round_coordinates']) {
$values['left'] -= 0.005;
$values['bottom'] -= 0.005;
$values['right'] += 0.005;
$values['top'] += 0.005;
foreach ($values as $k => $v) {
$values[$k] = round($values[$k], 2);
}
}
}
else {
$values = FALSE;
}
}
return $values;
}
}

View File

@@ -0,0 +1,69 @@
<?php
declare(strict_types = 1);
namespace Drupal\views_geojson\Plugin\views\argument_default;
use Drupal\core\form\FormStateInterface;
use Drupal\views\Plugin\views\argument_default\QueryParameter;
/**
* The BBOX query string argument default handler.
*
* @ingroup views_argument_default_plugins
*
* @ViewsArgumentDefault(
* id="bboxquery",
* title=@Translation("BBox Query"),
* )
*/
class BBoxQuery extends QueryParameter {
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['info'] = [
'#markup' => '<p class="description">Attempt to pull bounding box info
directly from the query string, bypassing Drupal\'s normal argument
handling. If the argument does not exist, all values will be shown.</p>',
];
$form['arg_id'] = [
'#type' => 'textfield',
'#title' => $this->t('Query argument ID'),
'#size' => 60,
'#maxlength' => 64,
'#default_value' => $this->options['arg_id'] ? $this->options['arg_id'] : $this->t('bbox'),
'#description' => $this->t('The ID of the query argument.<br />For OpenLayers use <em>bbox</em>, (as in "<em>?bbox=left,bottom,right,top</em>".)'),
];
}
/**
* Return the default argument.
*/
public function getArgument() {
$current_request = $this->view->getRequest();
if ($current_request->query->has($this->options['arg_id'])) {
return $current_request->query->get($this->options['arg_id']);
}
// TODO: What should be returned if arg not present, and empty result option
// is set or not ? Otherwise, use the fixed fallback value.
return $this->options['fallback'];
}
/**
* TODO: Determine if this is being implemented correctly.
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['argument'] = ['default' => ''];
$options['arg_id'] = ['default' => 'bbox'];
return $options;
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Drupal\views_geojson\Plugin\views\display;
use Drupal\rest\Plugin\views\display\RestExport;
/**
* The plugin that handles Data response callbacks for GeoJSON REST resources.
*
* @ingroup views_display_plugins
*
* @ViewsDisplay(
* id = "geojson_export",
* title = @Translation("GeoJSON export"),
* help = @Translation("Create a GeoJSON export resource."),
* uses_route = TRUE,
* admin = @Translation("GeoJSON export"),
* returns_response = TRUE
* )
*/
class GeoJsonExport extends RestExport {
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
// Set the default style plugin to 'geojson'.
$options['style']['contains']['type']['default'] = 'geojson';
$options['row']['contains']['type']['default'] = 'data_field';
return $options;
}
}

View File

@@ -0,0 +1,636 @@
<?php
declare(strict_types = 1);
namespace Drupal\views_geojson\Plugin\views\style;
use Drupal;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\style\StylePluginBase;
use Drupal\views\ResultRow;
use Exception;
use geoPHP;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use function count;
use function is_object;
use const JSON_HEX_AMP;
use const JSON_HEX_APOS;
use const JSON_HEX_QUOT;
use const JSON_HEX_TAG;
use const JSON_PRETTY_PRINT;
/**
* Style plugin to render view as GeoJSON code.
*
* @ingroup views_style_plugins
*
* @ViewsStyle(
* id="geojson",
* title=@Translation("GeoJSON"),
* theme="views_view_geojson",
* description=@Translation("Displays field data in GeoJSON data format."),
* display_types={"data"}
* )
*/
class GeoJson extends StylePluginBase {
/**
* The definition.
*
* @var array
*/
public $definition;
/**
* The serializer which serializes the views result.
*
* @var \Symfony\Component\Serializer\Serializer
*/
protected $serializer;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase::$usesFields.
*
* @var bool
*/
protected $usesFields = TRUE;
/**
* Overrides Drupal\views\Plugin\views\style\StylePluginBase::$usesGrouping.
*
* @var bool
*/
protected $usesGrouping = FALSE;
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase::$usesRowClass.
*
* @var bool
*/
protected $usesRowClass = FALSE;
/**
* Overrides \Drupal\views\Plugin\views\style\StylePluginBase::$usesRowPlugin.
*
* @var bool
*/
protected $usesRowPlugin = FALSE;
/**
* The serializer formats.
*
* @var array
*/
private $formats;
/**
* GeoJson constructor.
*
* @param array $configuration
* The configuration.
* @param string $plugin_id
* The plugin id.
* @param array $plugin_definition
* The plugin definition.
* @param \Symfony\Component\Serializer\SerializerInterface $serializer
* The serializer.
* @param array $serializer_formats
* The serializer formats.
*/
public function __construct(array $configuration, $plugin_id, array $plugin_definition, SerializerInterface $serializer, array $serializer_formats, ModuleHandlerInterface $module_handler) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->definition = $plugin_definition + $configuration;
$this->serializer = $serializer;
$this->formats = ['json', 'html'];
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$fields = [];
$fields_info = [];
// Get list of fields in this view & flag available geodata fields.
$handlers = $this->displayHandler->getHandlers('field');
$field_definition = $this->displayHandler->getOption('fields');
// Check for any fields, as the view needs them.
if (empty($handlers)) {
$form['error_markup'] = [
'#value' => $this->t('You need to enable at least one field before you can configure your field settings'),
'#prefix' => '<div class="error form-item description">',
'#suffix' => '</div>',
];
return;
}
// Go through fields, fill $fields and $fields_info arrays.
foreach ($this->displayHandler->getHandlers('field') as $field_id => $handler) {
$fields[$field_id] = $handler->definition['title'];
$fields_info[$field_id]['type'] = $field_definition[$field_id]['type'];
}
// Default data source.
$data_source_options = [
'latlon' => $this->t('Other: Lat/Lon Point'),
'geofield' => $this->t('Geofield'),
'geolocation' => $this->t('Geolocation'),
'wkt' => $this->t('WKT'),
];
// Data Source options.
$form['data_source'] = [
'#type' => 'fieldset',
'#tree' => TRUE,
'#title' => $this->t('Data Source'),
];
$form['data_source']['value'] = [
'#type' => 'select',
'#multiple' => FALSE,
'#title' => $this->t('Map Data Sources'),
'#description' => $this->t('Choose which sources of data that the map will provide features for.'),
'#options' => $data_source_options,
'#default_value' => $this->options['data_source']['value'],
];
// Other Lat and Lon data sources.
if (count($fields) > 0) {
$form['data_source']['latitude'] = [
'#type' => 'select',
'#title' => $this->t('Latitude Field'),
'#description' => $this->t('Choose a field for Latitude. This should be a field that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['latitude'],
'#states' => [
'visible' => [
':input[name="style_options[data_source][value]"]' => ['value' => 'latlon'],
],
],
];
$form['data_source']['longitude'] = [
'#type' => 'select',
'#title' => $this->t('Longitude Field'),
'#description' => $this->t('Choose a field for Longitude. This should be a field that is a decimal or float value.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['longitude'],
'#states' => [
'visible' => [
':input[name="style_options[data_source][value]"]' => ['value' => 'latlon'],
],
],
];
// Get Geofield-type fields.
$geofield_fields = [];
foreach ($fields as $field_id => $field) {
// @TODO We need to check if the field type is `geofield_default`. But
// at the moment this information is missing from the array, due to a
// bug with Geofield 8.x-1.x-dev. When the bug is fixed, we can add a
// check here again.
$geofield_fields[$field_id] = $field;
}
// Geofield.
$form['data_source']['geofield'] = [
'#type' => 'select',
'#title' => $this->t('Geofield'),
'#description' => $this->t("Choose a Geofield field. Any formatter will do; we'll access Geofield's underlying WKT format."),
'#options' => $geofield_fields,
'#default_value' => $this->options['data_source']['geofield'],
'#states' => [
'visible' => [
':input[name="style_options[data_source][value]"]' => ['value' => 'geofield'],
],
],
];
// Get Geofield-type fields.
$geolocation_fields = [];
foreach ($fields as $field_id => $field) {
// @todo - need to limit to just geolocation fields.
$geolocation_fields[$field_id] = $field;
}
// Geolocation.
$form['data_source']['geolocation'] = [
'#type' => 'select',
'#title' => $this->t('Geolocation'),
'#description' => $this->t("Choose a Geolocation field. Any formatter will do; we'll access Geolocation's underlying data storage."),
'#options' => $geolocation_fields,
'#default_value' => $this->options['data_source']['geolocation'],
'#states' => [
'visible' => [
':input[name="style_options[data_source][value]"]' => ['value' => 'geolocation'],
],
],
];
// WKT.
$form['data_source']['wkt'] = [
'#type' => 'select',
'#title' => $this->t('WKT'),
'#description' => $this->t('Choose a WKT format field.'),
'#options' => $fields,
'#default_value' => $this->options['data_source']['wkt'],
'#states' => [
'visible' => [
':input[name="style_options[data_source][value]"]' => ['value' => 'wkt'],
],
],
];
}
$form['data_source']['name_field'] = [
'#type' => 'select',
'#title' => $this->t('Title Field'),
'#description' => $this->t('Choose the field to appear as title on tooltips.'),
'#options' => array_merge(['' => ''], $fields),
'#default_value' => $this->options['data_source']['name_field'],
];
$form['data_source']['description_field'] = [
'#type' => 'select',
'#title' => $this->t('Description'),
'#description' => $this->t('Choose the field or rendering method to appear as
description on tooltips.'),
'#required' => FALSE,
'#options' => array_merge(['' => ''], $fields),
'#default_value' => $this->options['data_source']['description_field'],
];
// Attributes and variable styling description.
$form['attributes'] = [
'#type' => 'fieldset',
'#title' => $this->t('Attributes and Styling'),
'#description' => $this->t('Attributes are field data attached to each feature. This can be used with styling to create Variable styling.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
];
$form['jsonp_prefix'] = [
'#type' => 'textfield',
'#title' => $this->t('JSONP prefix'),
'#default_value' => $this->options['jsonp_prefix'],
'#description' => $this->t('If used the JSON output will be enclosed with parentheses and prefixed by this label, as in the JSONP format.'),
];
// Make array of attributes.
$variable_fields = [];
// Add name and description.
if (!empty($this->options['data_source']['name_field'])) {
$variable_fields['name'] = '${name}';
}
if (!empty($this->options['data_source']['description_field'])) {
$variable_fields['description'] = '${description}';
}
// Go through fields again to ID variable fields.
// TODO: is it necessary to call getHandlers twice or can we reuse data from
// $fields?
foreach ($this->displayHandler->getHandlers('field') as $field => $handler) {
if (($field !== $this->options['data_source']['name_field']) && ($field !== $this->options['data_source']['description_field'])) {
$variable_fields[$field] = '${' . $field . '}';
}
}
$markup = $this->t('Fields added to this view will be attached to their respective feature, (point, line, polygon,) as attributes.
These attributes can then be used to add variable styling to your themes. This is accomplished by using the %syntax
syntax in the values for a style. The following is a list of formatted variables that are currently available;
these can be placed right in the style interface.', ['%syntax' => '${field_name}']);
$form['attributes']['styling'][''] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#attributes' => [
'class' => [
'description',
],
],
'#markup' => $markup,
];
$form['attributes']['styling'][] = [
'#theme' => 'item_list',
'#items' => $variable_fields,
'#attributes' => ['class' => ['description']],
];
$form['attributes']['styling'][''] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#attributes' => [
'class' => [
'description',
],
],
'#value' => $this->t('Please note that this does not apply to Grouped Displays.'),
];
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('serializer'),
$container->getParameter('serializer.formats'),
$container->get('module_handler')
);
}
/**
* {@inheritdoc}
*/
public function getFormats() {
return ['json', 'html'];
}
/**
* {@inheritdoc}
*/
public function render() {
$features = [
'type' => 'FeatureCollection',
'features' => [],
];
// Get the excluded fields array, common for all rows.
$excluded_fields = $this->getExcludedFields();
// Render each row.
foreach ($this->view->result as $i => $row) {
$this->view->row_index = $i;
if ($feature = $this->renderRow($row, $excluded_fields)) {
$features['features'][] = $feature;
}
}
$this->moduleHandler->alter('geojson_view', $features, $this->view);
unset($this->view->row_index);
if (!empty($this->view->live_preview)) {
// Pretty-print the JSON.
$json = json_encode($features, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_PRETTY_PRINT);
}
else {
// Render the collection to JSON using Drupal standard renderer.
$json = Json::encode($features);
}
if (!empty($this->options['jsonp_prefix'])) {
$json = $this->options['jsonp_prefix'] . "({$json})";
}
// Everything else returns output.
return $json;
}
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['data_source'] = [
'contains' => [
'value' => ['default' => 'asc'],
'latitude' => ['default' => 0],
'longitude' => ['default' => 0],
'geofield' => ['default' => 0],
'geolocation' => ['default' => 0],
'wkt' => ['default' => 0],
'name_field' => ['default' => 0],
'description_field' => ['default' => 0],
],
];
$options['attributes'] = ['default' => NULL, 'translatable' => FALSE];
$options['jsonp_prefix'] = [
'default' => NULL,
'translatable' => FALSE,
];
return $options;
}
/**
* Retrieves the list of excluded fields due to style plugin configuration.
*
* @return array
* List of excluded fields.
*/
protected function getExcludedFields() {
$data_source = $this->options['data_source'];
$excluded_fields = [
$data_source['name_field'],
$data_source['description_field'],
];
switch ($data_source['value']) {
case 'latlon':
$excluded_fields[] = $data_source['latitude'];
$excluded_fields[] = $data_source['longitude'];
break;
case 'geofield':
$excluded_fields[] = $data_source['geofield'];
break;
case 'geolocation':
$excluded_fields[] = $data_source['geolocation'];
break;
case 'wkt':
$excluded_fields[] = $data_source['wkt'];
break;
}
return array_combine($excluded_fields, $excluded_fields);
}
/**
* Retrieves the description field value.
*
* @param \Drupal\views\ResultRow $row
* The result row.
*
* @return string
* The main field value.
*/
protected function renderDescriptionField(ResultRow $row) {
return $this->renderMainField($row, 'description_field');
}
/**
* Retrieves the main fields values.
*
* @param \Drupal\views\ResultRow $row
* The result row.
* @param string $field_name
* The main field name.
*
* @return string
* The main field value.
*/
protected function renderMainField(ResultRow $row, $field_name) {
if ($this->options['data_source'][$field_name]) {
if (empty($this->view->field[$this->options['data_source'][$field_name]]->view->row_index)) {
$this->view->field[$this->options['data_source'][$field_name]]->view->row_index = $row->index;
}
return $this->view->field[$this->options['data_source'][$field_name]]->advancedRender($row);
}
return '';
}
/**
* Retrieves the name field value.
*
* @param \Drupal\views\ResultRow $row
* The result row.
*
* @return string
* The main field value.
*/
protected function renderNameField(ResultRow $row) {
return $this->renderMainField($row, 'name_field');
}
/**
* Render views fields to GeoJSON.
*
* Takes each field from a row object and renders the field as determined by
* the field's theme.
*
* @param \Drupal\views\ResultRow $row
* Row object.
* @param array $excluded_fields
* Array containing field keys to be excluded.
*
* @throws Exception
*
* @return array
* Array containing all the raw and rendered fields
*/
protected function renderRow(ResultRow $row, array $excluded_fields) {
$feature = ['type' => 'Feature'];
$data_source = $this->options['data_source'];
// Pre-render fields to handle those rewritten with tokens.
foreach ($this->view->field as $field_idx => $field) {
$field->advancedRender($row);
}
switch ($data_source['value']) {
case 'latlon':
$latitude = (string) $this->view->field[$data_source['latitude']]->advancedRender($row);
$longitude = (string) $this->view->field[$data_source['longitude']]->advancedRender($row);
if (!empty($latitude) && !empty($longitude)) {
$feature['geometry'] = [
'type' => 'Point',
'coordinates' => [(float) $longitude, (float) $latitude],
];
}
break;
case 'geofield':
$geofield = $this->view->style_plugin->getFieldValue($row->index, $data_source['geofield']);
if (!empty($geofield)) {
$geometry = Drupal::getContainer()->get('geofield.geophp')->load($geofield);
if (is_object($geometry)) {
$feature['geometry'] = Json::decode($geometry->out('json'));
}
}
break;
case 'geolocation':
$geo_items = $this->view->field[$data_source['geolocation']]->getItems($row);
if (!empty($geo_items[0]['raw'])) {
$raw_geo_item = $geo_items[0]['raw'];
$wkt = "POINT({$raw_geo_item->lng} {$raw_geo_item->lat})";
$geometry = geoPHP::load($wkt, 'wkt');
if (is_object($geometry)) {
$feature['geometry'] = Json::decode($geometry->out('json'));
}
}
break;
case 'wkt':
$wkt = (string) $this->view->field[$data_source['wkt']]->advancedRender($row);
if (!empty($wkt)) {
$wkt = explode(',', $wkt);
$geometry = geoPHP::load($wkt, 'wkt');
if (is_object($geometry)) {
$feature['geometry'] = Json::decode($geometry->out('json'));
}
}
break;
}
// Only add features with geometry data.
if (empty($feature['geometry'])) {
return;
}
// Add the name and description attributes
// as chosen through interface.
$feature['properties']['name'] = $this->renderNameField($row);
$feature['properties']['description'] = $this->renderDescriptionField($row);
// Fill in attributes that are not:
// - Coordinate fields,
// - Name/description (already processed),
// - Views "excluded" fields.
foreach (array_keys($this->view->field) as $id) {
$field = $this->view->field[$id];
if (!isset($excluded_fields[$id]) && !($field->options['exclude'])) {
// Allows you to customize the name of the property by setting a label
// to the field.
$key = empty($field->options['label']) ? $id : $field->options['label'];
$value_rendered = $field->advancedRender($row);
$feature['properties'][$key] = is_numeric($value_rendered) ? (float) $value_rendered : $value_rendered;
}
}
return $feature;
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* @file
* Hooks related to views_geojson module.
*/
use Drupal\views\ViewExecutable;
/**
* @addtogroup hooks
* @{
*/
/**
* Alter geojson view render array immediately before rendering.
*
* @param array $features
* The array of features.
* @param \Drupal\views\ViewExecutable $view
* The current view.
*/
function hook_geojson_view_alter(array &$features, ViewExecutable $view) {
}
/**
* @} End of "addtogroup hooks".
*/

View File

@@ -0,0 +1,14 @@
name: Views GeoJSON
type: module
description: Provides a Views feed style for GeoJSON output.
core_version_requirement: ^8 || ^9 || ^10
package: Views
dependencies:
- drupal:views
- drupal:serialization
- drupal:rest
# Information added by Drupal.org packaging script on 2022-09-16
version: '8.x-1.2'
project: 'views_geojson'
datestamp: 1663370949

View File

@@ -0,0 +1,31 @@
<?php
/**
* @file
* Views plugin definition.
*/
declare(strict_types = 1);
/**
* Implements hook_views_data().
*
* Adds bounding box contextual filter.
*/
function views_geojson_views_data() {
$data = [];
$data['views']['views_geojson_bbox_argument'] = [
'group' => t('Views GeoJSON'),
'real field' => 'bbox_argument',
'title' => t('Bounding box'),
'help' => t('Limit the results to those within a geospatial bounding box. Can be used in conjunction with Leaflet.'),
'argument' => [
'id' => 'views_geojson_bbox_argument',
'label' => t('Bounding box'),
'empty field name' => '- No value -',
],
];
return $data;
}