Merge tag '1.3.0'

This commit is contained in:
David Molineus
2018-02-23 14:13:05 +01:00
17 changed files with 728 additions and 192 deletions

View File

@@ -4,12 +4,18 @@ php:
- "5.6"
- "7.0"
- "7.1"
- "7.2"
env:
- CONTAO_VERSION=contao/core-bundle ^4.4.2
- CONTAO_VERSION=contao/core-bundle ~4.4.2
- CONTAO_VERSION=contao/core-bundle ~4.5.0
matrix:
exclude:
- php: 5.6
env: CONTAO_VERSION=contao/core-bundle ~4.5.0
- php: 7.0
env: CONTAO_VERSION=contao/core-bundle ~4.5.0
sudo: false

View File

@@ -2,6 +2,16 @@
Changelog
=========
Version 1.3.0 (2018-02-xx)
--------------------------
[Full Changelog](https://github.com/netzmacht/contao-leaflet-geocode-widget/compare/1.2.1...1.3.0)
- Move apply button to the modal footer.
- Deprecate `Netzmacht\Contao\Leaflet\GeocodeWidget`. Use `Netzmacht\Contao\Leaflet\Widget\GeocodeWidget` instead.
- Add feature to adjust a radius.
- Allow Contao 4.5.0.
Version 1.2.0 (2017-11-13)
--------------------------

View File

@@ -51,6 +51,8 @@ bin/console assets:install --symlink
### 4. Use the widget
#### Coordinates only
```php
$GLOBALS['TL_DCA']['tl_example']['fields']['coordinates'] = [
'label' => ['Koordinaten', 'Geben Sie die Koordinaten ein'],
@@ -61,3 +63,52 @@ $GLOBALS['TL_DCA']['tl_example']['fields']['coordinates'] = [
'sql' => 'varchar(255) NOT NULL default \'\''
];
```
#### Coordinates and radius
To pick the radius in meters as well, you have to configure the `eval.radius` option for the related radius field.
The radius field should be a simle text input. The `default`, `minval` and `maxval` flags are passed to the geocode
widget so that only radius in that boundary can be chosen.
```php
$GLOBALS['TL_DCA']['tl_page']['fields']['coordinates'] = [
'label' => ['Koordinaten', 'Geben Sie die Koordinaten ein'],
'inputType' => 'leaflet_geocode',
'eval' => [
'tl_class' => 'w50',
'radius' => 'radius'
],
'sql' => 'varchar(255) NOT NULL default \'\''
];
$GLOBALS['TL_DCA']['tl_page']['fields']['radius'] = [
'label' => ['Radius', 'Angabe des Radius in Metern'],
'inputType' => 'leaflet_radius', // Optional, you can use a text widget as well
'eval' => [
'default' => 500,
'minval' => 100,
'maxval' => 5000,
'steps' => 100, // Round value to the closest 100m.
'tl_class' => 'w50',
],
'sql' => 'varchar(255) NOT NULL default \'\''
];
```
If you want to add an wizard icon to the radius field as well, you only have to reference the coordinates field.
```php
$GLOBALS['TL_DCA']['tl_page']['fields']['radius'] = [
'label' => ['Radius', 'Angabe des Radius in Metern'],
'inputType' => 'leaflet_radius',
'eval' => [
'rgxp' => 'natural',
'default' => 500,
'minval' => 100,
'maxval' => 5000,
'tl_class' => 'w50 wizard',
'coordinates' => 'coordinates'
],
'sql' => 'varchar(255) NOT NULL default \'\''
];
```

View File

@@ -8,13 +8,13 @@
"leaflet"
],
"type": "contao-bundle",
"license": "LGPL-3.0+",
"license": "LGPL-3.0-or-later",
"authors": [
{
"name": "David Molineus",
"email": "mail@netzmacht.de",
"homepage": "http://www.netzmacht.de",
"role": "Project leader"
"homepage": "https://netzmacht.de",
"role": "Developer"
}
],
"support": {
@@ -25,12 +25,13 @@
},
"require": {
"php": ">=5.6.0",
"contao/core-bundle": "~4.4.0",
"netzmacht/contao-leaflet-libraries": "~1.0"
"contao/core-bundle": "^4.4.0",
"netzmacht/contao-leaflet-libraries": "~1.3"
},
"require-dev": {
"contao/manager-plugin": "^2.0",
"phpcq/all-tasks": "^1.2"
"phpcq/all-tasks": "^1.2",
"php-http/guzzle6-adapter": "^1.1"
},
"suggest": {
"netzmacht/contao-leaflet-maps": "Leaflet Maps for Contao"
@@ -42,8 +43,8 @@
},
"extra": {
"branch-alias": {
"dev-master": "1.2.x-dev",
"dev-develop": "1.3.x-dev"
"dev-master": "1.3.x-dev",
"dev-develop": "1.4.x-dev"
},
"contao-manager-plugin": "Netzmacht\\Contao\\Leaflet\\GeocodeWidget\\ContaoManager\\Plugin"
}

View File

@@ -0,0 +1,37 @@
<?php
/**
* Geocode backend widget based on Leaflet.
*
* @package netzmacht
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2016-2018 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0 https://github.com/netzmacht/contao-leaflet-geocode-widget/blob/master/LICENSE
* @filesource
*/
namespace Netzmacht\Contao\Leaflet\GeocodeWidget\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
/**
* Class LeafletGeocodeWidgetExtension
*/
class LeafletGeocodeWidgetExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader(
$container,
new FileLocator(dirname(__DIR__) . '/Resources/config')
);
$loader->load('listeners.yml');
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Geocode backend widget based on Leaflet.
*
* @package netzmacht
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2016-2018 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0 https://github.com/netzmacht/contao-leaflet-geocode-widget/blob/master/LICENSE
* @filesource
*/
namespace Netzmacht\Contao\Leaflet\GeocodeWidget\EventListener;
use Contao\DataContainer;
/**
* Class RadiusWizardCallbackListener
*
* @package Netzmacht\Contao\Leaflet\GeocodeWidget\EventListener
*/
class RadiusWizardCallbackListener
{
/**
* Generate the wizard for the radius widget.
*
* @param DataContainer $dataContainer Data container driver.
*
* @return string
*
* @SuppressWarnings(PHPMD.Superglobals)
*/
public function generateWizard($dataContainer)
{
if (!isset($GLOBALS['TL_DCA'][$dataContainer->table]['fields'][$dataContainer->field]['eval']['coordinates'])) {
return '';
}
return sprintf(
'<a href="#" onclick="$(\'ctrl_%s_toggle\').click();return false;"><img src="%s"></a>',
$GLOBALS['TL_DCA'][$dataContainer->table]['fields'][$dataContainer->field]['eval']['coordinates'],
'bundles/leafletgeocodewidget/img/map.png'
);
}
}

View File

@@ -5,130 +5,38 @@
*
* @package netzmacht
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2016-2017 netzmacht David Molineus. All rights reserved.
* @copyright 2016-2018 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0 https://github.com/netzmacht/contao-leaflet-geocode-widget/blob/master/LICENSE
* @filesource
*/
namespace Netzmacht\Contao\Leaflet\GeocodeWidget;
use Netzmacht\Contao\Leaflet\GeocodeWidget\Widget\GeocodeWidget as BaseWidget;
/**
* Class GeocodeWidget
*
* @property int size
* @property bool multiple
* @deprecated
*/
class GeocodeWidget extends \Widget
class GeocodeWidget extends BaseWidget
{
/**
* Submit user input.
*
* @var boolean
* {@inheritdoc}
*/
protected $blnSubmitInput = true;
/**
* Add a for attribute.
*
* @var boolean
*/
protected $blnForAttribute = true;
/**
* Template.
*
* @var string
*/
protected $strTemplate = 'be_widget';
/**
* Template name.
*
* @var string
*/
protected $widgetTemplate = 'be_widget_leaflet_geocode';
/**
* Validate the input.
*
* @param mixed $value Given value.
*
* @return mixed
*
* @SuppressWarnings(PHPMD.Superglobals)
*/
protected function validator($value)
public function __construct(array $arrAttributes = null)
{
$value = parent::validator($value);
parent::__construct($arrAttributes);
if (!$value) {
return $value;
}
if (is_array($value)) {
foreach ($value as $key => $val) {
$value[$key] = $this->validator($val);
}
return $value;
}
// See: http://stackoverflow.com/a/18690202
if (!preg_match(
'#^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)(,[-+]?\d+)?$#',
$value
)) {
$this->addError(
sprintf(
$GLOBALS['TL_LANG']['ERR']['leafletInvalidCoordinate'],
$value
)
);
}
return $value;
}
/**
* Generate the widget.
*
* @return string
*/
public function generate()
{
$wrapperClass = 'wizard';
if (!$this->multiple || !$this->size) {
$this->size = 1;
} else {
$wrapperClass .= ' wizard_' . $this->size;
}
if (!is_array($this->value)) {
$this->value = [$this->value];
}
$buffer = '';
for ($index = 0; $index < $this->size; $index++) {
$template = new \BackendTemplate($this->widgetTemplate);
$template->setData(
[
'wrapperClass' => $wrapperClass,
'widget' => $this,
'value' => \StringUtil::specialchars($this->value[$index]),
'class' => $this->strClass ? ' ' . $this->strClass : '',
'id' => $this->strId . (($this->size > 1) ? '_' . $index : ''),
'name' => $this->strName . (($this->size > 1) ? '[]' : ''),
'attributes' => $this->getAttributes(),
'wizard' => $this->wizard,
'label' => $this->strLabel,
]
);
$buffer .= $template->parse();
}
return $buffer;
// @codingStandardsIgnoreStart
@trigger_error(
sprintf(
'"%s" is deprecated and will be removed in version 2.0.0. Use "%s" instead.',
GeocodeWidget::class,
BaseWidget::class
),
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
}
}

View File

@@ -0,0 +1,4 @@
services:
netzmacht.contao_leaflet_geocode.listeners.radius_wizard:
class: Netzmacht\Contao\Leaflet\GeocodeWidget\EventListener\RadiusWizardCallbackListener
public: true

View File

@@ -5,9 +5,10 @@
*
* @package netzmacht
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2016-2017 netzmacht David Molineus. All rights reserved.
* @copyright 2016-2018 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0 https://github.com/netzmacht/contao-leaflet-geocode-widget/blob/master/LICENSE
* @filesource
*/
$GLOBALS['BE_FFL']['leaflet_geocode'] = 'Netzmacht\Contao\Leaflet\GeocodeWidget\GeocodeWidget';
$GLOBALS['BE_FFL']['leaflet_geocode'] = 'Netzmacht\Contao\Leaflet\GeocodeWidget\Widget\GeocodeWidget';
$GLOBALS['BE_FFL']['leaflet_radius'] = 'Netzmacht\Contao\Leaflet\GeocodeWidget\Widget\RadiusWidget';

View File

@@ -13,3 +13,6 @@
$GLOBALS['TL_LANG']['ERR']['leafletInvalidCoordinate'] = 'Die angegebenen Koordinaten sind ungültig.';
$GLOBALS['TL_LANG']['MSC']['leafletSearchPositionLabel'] = 'Suchen';
$GLOBALS['TL_LANG']['MSC']['leafletApplyPositionLabel'] = 'Übernehmen';
$GLOBALS['TL_LANG']['MSC']['leafletConfirmPositionLabel'] = 'Als neue Position übernehmen?';
$GLOBALS['TL_LANG']['MSC']['leafletOkLabel'] = 'Ja';
$GLOBALS['TL_LANG']['MSC']['leafletCancelLabel'] = 'Nein';

View File

@@ -10,6 +10,9 @@
* @filesource
*/
$GLOBALS['TL_LANG']['ERR']['leafletInvalidCoordinate'] = 'Invalid coordinates given.';
$GLOBALS['TL_LANG']['MSC']['leafletSearchPositionLabel'] = 'Search';
$GLOBALS['TL_LANG']['MSC']['leafletApplyPositionLabel'] = 'Apply';
$GLOBALS['TL_LANG']['ERR']['leafletInvalidCoordinate'] = 'Invalid coordinates given.';
$GLOBALS['TL_LANG']['MSC']['leafletSearchPositionLabel'] = 'Search';
$GLOBALS['TL_LANG']['MSC']['leafletApplyPositionLabel'] = 'Apply';
$GLOBALS['TL_LANG']['MSC']['leafletConfirmPositionLabel'] = 'Set as new position';
$GLOBALS['TL_LANG']['MSC']['leafletOkLabel'] = 'Ok';
$GLOBALS['TL_LANG']['MSC']['leafletCancelLabel'] = 'Cancel';

View File

@@ -6,6 +6,12 @@ $GLOBALS['TL_CSS'][] = 'bundles/leafletgeocodewidget/css/backend.css';
$GLOBALS['TL_JAVASCRIPT'][] = 'assets/leaflet/libs/leaflet/leaflet.js';
$GLOBALS['TL_JAVASCRIPT'][] = 'assets/leaflet/libs/control-geocoder/Control.Geocoder.js';
if ($this->radius) {
$GLOBALS['TL_CSS'][] = 'assets/leaflet/libs/leaflet-pm/leaflet.pm.css';
$GLOBALS['TL_JAVASCRIPT'][] = 'assets/leaflet/libs/leaflet-pm/leaflet.pm.min.js';
}
$GLOBALS['TL_JAVASCRIPT'][] = 'bundles/leafletgeocodewidget/js/geocode.widget.js';
?>
@@ -19,15 +25,26 @@ $GLOBALS['TL_JAVASCRIPT'][] = 'bundles/leafletgeocodewidget/js/geocode.widget.js
onfocus="Backend.getScrollOffset()"
>
<img src="bundles/leafletgeocodewidget/img/map.png" id="ctrl_<?= $this->id ?>_toggle">
<a href="#"><img src="bundles/leafletgeocodewidget/img/map.png" id="ctrl_<?= $this->id ?>_toggle"></a>
</div>
<?= $this->wizard ?>
<script>
new LeafletGeocodeWidget({
id: 'ctrl_<?= $this->id ?>',
searchPositionLabel: '<?= $GLOBALS['TL_LANG']['MSC']['leafletSearchPositionLabel'] ?>',
applyPositionLabel: '<?= $GLOBALS['TL_LANG']['MSC']['leafletApplyPositionLabel'] ?>',
modalTitle: '<?= $this->label ?>'
})
window.addEvent(
'domready',
function () {
new LeafletGeocodeWidget({
id: 'ctrl_<?= $this->id ?>',
searchPositionLabel: '<?= $GLOBALS['TL_LANG']['MSC']['leafletSearchPositionLabel'] ?>',
applyPositionLabel: '<?= $GLOBALS['TL_LANG']['MSC']['leafletApplyPositionLabel'] ?>',
confirmPositionLabel: '<?= $GLOBALS['TL_LANG']['MSC']['leafletConfirmPositionLabel'] ?>',
okLabel: '<?= $GLOBALS['TL_LANG']['MSC']['leafletOkLabel'] ?>',
cancelLabel: '<?= $GLOBALS['TL_LANG']['MSC']['leafletCancelLabel'] ?>',
modalTitle: '<?= $this->label ?>'<?php if ($this->radius): ?>,
radius: <?= json_encode($this->radius) ?>,
picker: LeafletGeocodeCirclePicker
<?php endif ?>
})
}
);
</script>

View File

@@ -0,0 +1,13 @@
<div class="<?= $this->wrapperClass ?>">
<input type="text"
name="<?= $this->name ?>"
id="ctrl_<?= $this->id ?>"
class="tl_text tl_leaflet_geocode<?= $this->class ?>"
value="<?= $this->value ?>"<?= $this->attributes ?>
onfocus="Backend.getScrollOffset()"
>
<?php if ($this->coordinates): ?>
<a href="#" onclick="$('ctrl_<?= $this->coordinates ?>_toggle').click();return false;"><img src="bundles/leafletgeocodewidget/img/map.png"></a>,
<?php endif ?>
</div>

View File

@@ -2,3 +2,25 @@
width: 325px;
display: inline-block;
}
.leaflet-geocode-map {
width: 100%;
height: 50vh;
min-height: 400px
}
.leaflet-geocode-btn {
margin-top: 10px;
display: inline-block;
padding: 7px 12px;
border: 1px solid #aaa;
border-radius: 2px;
box-sizing: border-box;
cursor: pointer;
background: #eee;
transition: background .2s ease;
}
.leaflet-geocode-btn + .leaflet-geocode-btn {
margin-left: 5px;
}

View File

@@ -3,18 +3,151 @@
*
* @package netzmacht
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2016-2017 netzmacht David Molineus. All rights reserved.
* @copyright 2016-2018 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0 https://github.com/netzmacht/contao-leaflet-geocode-widget/blob/master/LICENSE
* @filesource
*/
var LeafletGeocodeAbstractPicker = L.Class.extend({
initialize: function (map, options) {
L.Util.setOptions(this, options);
this.map = map;
},
show: function (position, radius) {
if (!this.marker) {
this._createMarker(position, radius);
} else {
this._updateCoordinates(position, radius);
}
this._panTo(position);
},
_updateCoordinates: function (position) {
this.marker.setLatLng(position);
}
});
var LeafletGeocodeMarkerPicker = LeafletGeocodeAbstractPicker.extend({
apply: function (coordinatesInput) {
var coordinates = this.marker
? ( this.marker.getLatLng().lat + ',' + this.marker.getLatLng().lng)
: '';
coordinatesInput.set('value', coordinates);
},
_panTo: function (position) {
this.map.setZoom(this.map.getMaxZoom());
this.map.panTo(position);
},
_createMarker: function (position) {
this.marker = L.marker(position, {draggable: true}).addTo(this.map);
this.marker.on('dragend', function () {
this.map.panTo(this.marker.getLatLng());
}.bind(this));
}
});
var LeafletGeocodeCirclePicker = LeafletGeocodeAbstractPicker.extend({
apply: function (coordinatesInput, radiusInput) {
var radius = '';
var coordinates = this.marker
? ( this.marker.getLatLng().lat + ',' + this.marker.getLatLng().lng)
: '';
coordinatesInput.set('value', coordinates);
if (this.marker) {
radius = Math.round(this.marker.getRadius());
if (this.options.radius.steps > 0) {
radius = (this.options.radius.steps * Math.round(radius / this.options.radius.steps));
}
}
radiusInput.set('value', radius);
},
_panTo: function () {
this.map.fitBounds(this.marker.getBounds());
},
_createMarker: function (position, radius) {
this.marker = L.circle(position, { radius: radius || this.options.radius.default });
this.marker.addTo(this.map);
this.marker.on('pm:markerdragend', function () {
var radius = this.marker.getRadius();
if (this.options.radius.steps > 0) {
radius = (this.options.radius.steps * Math.round(radius / this.options.radius.steps));
}
if (this.options.radius.min > 0 && this.options.radius.min > radius) {
radius = this.options.radius.min;
}
if (this.options.radius.max > 0 && this.options.radius.max < radius) {
radius = this.options.radius.max;
}
if (radius != this.marker.getRadius()) {
this.marker.pm.disable();
this.marker.setRadius(radius);
this._enableEditMode();
} else {
this.marker.pm._outerMarker.setTooltipContent(this._formatRadius(radius));
}
this.map.fitBounds(this.marker.getBounds());
}.bind(this));
this._enableEditMode();
},
_updateCoordinates: function (position,radius) {
this.marker.pm.disable();
this.marker.setLatLng(position);
if (radius !== undefined) {
this.marker.setRadius(radius);
}
this.marker.pm.enable();
},
_enableEditMode: function () {
this.marker.pm.enable();
this.marker.pm._outerMarker.bindTooltip(
this._formatRadius(this.marker.getRadius()),
{permanent: true, direction: 'right', offset: [10, 0] }
);
},
_formatRadius: function (radius) {
var unit = 'm';
radius = Math.floor(radius);
if (radius > 1000) {
unit = 'km';
radius = (radius / 1000).toFixed(1);
}
return radius.toString() + ' ' + unit;
}
});
var LeafletGeocodeWidget = L.Class.extend({
options: {
mapTemplate: '<div id="leaflet_geocode_widget_map_{id}" class="" style="width 100%; height: 50vh; min-height: 400px"></div>',
mapTemplate: '<div id="leaflet_geocode_widget_map_{id}" class="leaflet-geocode-map"></div>',
modalWidth: 800,
modalTitle: 'Choose coordinates',
searchPositionLabel: 'Search',
applyPositionLabel: 'Apply'
applyPositionLabel: 'Apply',
confirmPositionLabel: 'Set as new position',
okLabel: 'Ok',
cancelLabel: 'Cancel',
radius: null,
picker: LeafletGeocodeMarkerPicker,
map: {
maxZoom: 15,
minZoom: 2
},
bboxPadding: [0, 70]
},
initialize: function (options) {
L.Util.setOptions(this, options);
@@ -22,40 +155,94 @@ var LeafletGeocodeWidget = L.Class.extend({
this.element = $(this.options.id);
this.toggle = $(this.options.id + '_toggle');
this.toggle.addEvent('click', this._showMap.bind(this));
if (this.options.radius) {
this.radius = $(this.options.radius.element);
if (this.radius.get('value').length > 0) {
this.options.radius.default = parseInt(this.radius.get('value'));
}
if (this.options.radius.default === undefined) {
this.options.radius.default = 0;
}
}
},
_showMap: function () {
var content, modal;
_showMap: function (e) {
e.stop();
// Create modal window.
content = L.Util.template(this.options.mapTemplate, this.options);
modal = this._createModal();
var content = L.Util.template(this.options.mapTemplate, this.options);
this.modal = this._createModal();
modal.show({'title': this.options.modalTitle, 'contents': content});
this.modal.show({title: this.options.modalTitle, contents: content});
// Initialize map after showing modal so element exists.
this._createMap(modal);
this._createMap();
},
_createModal: function () {
return new SimpleModal({
'width': this.options.modalWidth,
'hideFooter': true,
'draggable': false,
'overlayOpacity': .5,
'onShow': function () {
var modal = new SimpleModal({
width: this.options.modalWidth,
hideFooter: false,
draggable: false,
overlayOpacity: .5,
btn_ok: Contao.lang.close,
onShow: function () {
document.body.setStyle('overflow', 'hidden');
},
'onHide': function () {
onHide: function () {
document.body.setStyle('overflow', 'auto');
}
});
modal.addButton(Contao.lang.apply, 'btn', function () {
this.picker.apply(this.element, this.radius);
modal.hide();
}.bind(this));
return modal;
},
_createMap: function (modal) {
var map = L.map('leaflet_geocode_widget_map_' + this.options.id).setView([0, 0], 2);
_createMap: function () {
var map = L.map('leaflet_geocode_widget_map_' + this.options.id, this.options.map).setView([0, 0], 2);
var radius = 0;
this.picker = new this.options.picker(map, this.options);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
map.on('click', function (event) {
var marker = new L.marker(event.latlng).addTo(map);
var container = document.createElement('div');
var okButton = document.createElement('button');
var cancelButton = document.createElement('button');
okButton.set('class', 'leaflet-geocode-btn').appendHTML(this.options.okLabel);
okButton.addEvent('click', function (event) {
event.stop();
this.picker.show(marker.getLatLng());
map.removeLayer(marker);
}.bind(this));
cancelButton.set('class', 'leaflet-geocode-btn').appendHTML(this.options.cancelLabel);
cancelButton.addEvent('click', function (event) {
map.removeLayer(marker);
});
container.appendHTML('<h2>' + this.options.confirmPositionLabel + '</h2>');
container.appendChild(okButton);
container.appendChild(cancelButton);
marker.bindPopup(container, {
keepInView: true,
autoPanPaddingTopLeft: this.options.bboxPadding,
autoClose: false,
closeOnClick: false,
closeButton: false
}).openPopup();
}.bind(this));
var geoCoder = L.Control.geocoder({
defaultMarkGeocode: false,
collapsed: false,
@@ -63,53 +250,15 @@ var LeafletGeocodeWidget = L.Class.extend({
}).addTo(map);
geoCoder.on('markgeocode', function (event) {
this._handleGeoCode.call(this, modal, map, event);
this.picker.show(event.geocode.center);
}.bind(this));
if (this.element.value) {
var value = this.element.value.split(/,/);
this._createMarker(value, map);
if (this.radius && this.radius.get('value').length > 0) {
radius = parseInt(this.radius.get('value'));
}
map.setZoom(16);
map.panTo(value);
this.picker.show(L.latLng(this.element.value.split(/,/)), radius);
}
return map;
},
_handleGeoCode: function (modal, map, event) {
var container = document.createElement('div');
var link = document.createElement('button');
var result = event.geocode;
link.set('style', 'margin-left: 10px;');
link.appendText(this.options.applyPositionLabel);
link.addEvent('click', function (e) {
e.stop();
this.element.set('value', result.center.lat + ',' + result.center.lng);
modal.hide();
}.bind(this));
container.appendHTML(result.html || result.name);
container.appendChild(link);
if (this._geocodeMarker) {
map.removeLayer(this._geocodeMarker);
}
map.fitBounds(result.bbox, { padding: [0, 70]});
map.panTo(result.center);
this._createMarker(result.center, map);
this._geocodeMarker.bindPopup(container, {
keepInView: true,
autoPanPaddingTopLeft: [0, 70]
}).openPopup();
},
_createMarker: function (position, map) {
this._geocodeMarker = L.marker(position, {draggable: true}).addTo(map);
this._geocodeMarker.on('dragend', function (event) {
this.element.set('value', event.target._latlng.lat + ',' + event.target._latlng.lng);
}.bind(this));
}
});

View File

@@ -0,0 +1,167 @@
<?php
/**
* Geocode backend widget based on Leaflet.
*
* @package netzmacht
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2016-2018 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0 https://github.com/netzmacht/contao-leaflet-geocode-widget/blob/master/LICENSE
* @filesource
*/
namespace Netzmacht\Contao\Leaflet\GeocodeWidget\Widget;
/**
* Class GeocodeWidget
*
* @property int size
* @property bool multiple
*/
class GeocodeWidget extends \Widget
{
/**
* Submit user input.
*
* @var boolean
*/
protected $blnSubmitInput = true;
/**
* Add a for attribute.
*
* @var boolean
*/
protected $blnForAttribute = true;
/**
* Template.
*
* @var string
*/
protected $strTemplate = 'be_widget';
/**
* Template name.
*
* @var string
*/
protected $widgetTemplate = 'be_widget_leaflet_geocode';
/**
* Validate the input.
*
* @param mixed $value Given value.
*
* @return mixed
*
* @SuppressWarnings(PHPMD.Superglobals)
*/
protected function validator($value)
{
$value = parent::validator($value);
if (!$value) {
return $value;
}
if (is_array($value)) {
foreach ($value as $key => $val) {
$value[$key] = $this->validator($val);
}
return $value;
}
// See: http://stackoverflow.com/a/18690202
if (!preg_match(
'#^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)(,[-+]?\d+)?$#',
$value
)) {
$this->addError(
sprintf(
$GLOBALS['TL_LANG']['ERR']['leafletInvalidCoordinate'],
$value
)
);
}
return $value;
}
/**
* Generate the widget.
*
* @return string
*/
public function generate()
{
$wrapperClass = 'wizard';
if (!$this->multiple || !$this->size) {
$this->size = 1;
} else {
$wrapperClass .= ' wizard_' . $this->size;
}
if (!is_array($this->value)) {
$this->value = [$this->value];
}
$buffer = '';
for ($index = 0; $index < $this->size; $index++) {
$template = new \BackendTemplate($this->widgetTemplate);
$template->setData(
[
'wrapperClass' => $wrapperClass,
'widget' => $this,
'value' => \StringUtil::specialchars($this->value[$index]),
'class' => $this->strClass ? ' ' . $this->strClass : '',
'id' => $this->strId . (($this->size > 1) ? '_' . $index : ''),
'name' => $this->strName . (($this->size > 1) ? '[]' : ''),
'attributes' => $this->getAttributes(),
'wizard' => $this->wizard,
'label' => $this->strLabel,
'radius' => $this->buildRadiusOptions()
]
);
$buffer .= $template->parse();
}
return $buffer;
}
/**
* Build the radius options.
*
* @return array|null
*
* @SuppressWarnings(PHPMD.Superglobals)
*/
private function buildRadiusOptions()
{
if (!$this->radius || !isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->radius])) {
return null;
}
$options = [
'element' => 'ctrl_' . $this->radius,
'min' => 0,
'max' => 0,
'defaultValue' => 0
];
if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->radius]['eval'])) {
$config = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->radius]['eval'];
$options['min'] = isset($config['minval']) ? (int) $config['minval'] : 0;
$options['max'] = isset($config['maxval']) ? (int) $config['maxval'] : 0;
$options['defaultValue'] = isset($config['default']) ? (int) $config['default'] : 0;
$options['steps'] = isset($config['steps']) ? (int) $config['steps'] : 0;
}
return $options;
}
}

View File

@@ -0,0 +1,99 @@
<?php
/**
* Geocode backend widget based on Leaflet.
*
* @package netzmacht
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2016-2018 netzmacht David Molineus. All rights reserved.
* @license LGPL-3.0 https://github.com/netzmacht/contao-leaflet-geocode-widget/blob/master/LICENSE
* @filesource
*/
namespace Netzmacht\Contao\Leaflet\GeocodeWidget\Widget;
use Contao\BackendTemplate;
use Contao\TextField;
/**
* Class RadiusWidget
*/
class RadiusWidget extends TextField
{
/**
* Template name.
*
* @var string
*/
protected $widgetTemplate = 'be_widget_leaflet_radius';
/**
* {@inheritdoc}
*/
public function __get($strKey)
{
if ($strKey === 'rgxp') {
return 'natural';
}
return parent::__get($strKey);
}
/**
* Generate the widget.
*
* @return string
*/
public function generate()
{
$wrapperClass = $this->coordinates ? 'wizard' : '';
if (!$this->multiple || !$this->size) {
$this->size = 1;
} else {
$wrapperClass .= ' wizard_' . $this->size;
}
if (!is_array($this->value)) {
$this->value = [$this->value];
}
$buffer = '';
for ($index = 0; $index < $this->size; $index++) {
$template = new BackendTemplate($this->widgetTemplate);
$template->setData(
[
'wrapperClass' => trim($wrapperClass),
'widget' => $this,
'value' => \StringUtil::specialchars($this->value[$index]),
'class' => $this->strClass ? ' ' . $this->strClass : '',
'id' => $this->strId . (($this->size > 1) ? '_' . $index : ''),
'name' => $this->strName . (($this->size > 1) ? '[]' : ''),
'attributes' => $this->getAttributes(),
'wizard' => $this->wizard,
'label' => $this->strLabel,
'coordinates' => $this->coordinates
]
);
$buffer .= $template->parse();
}
return $buffer;
}
/**
* {@inheritdoc}
*/
protected function validator($varInput)
{
if (is_numeric($varInput) && $this->steps > 0) {
$steps = (int) $this->steps;
$varInput = (int) $varInput;
$varInput = ($steps * round($varInput / $steps));
}
return parent::validator($varInput);
}
}