Rearrange assets.

This commit is contained in:
David Molineus
2017-10-09 16:05:34 +02:00
parent 249b12cb61
commit b898aafe51
10 changed files with 4 additions and 4 deletions

310
js/Contao.js Normal file
View File

@@ -0,0 +1,310 @@
/**
* Leaflet integration into contao.
*
* This class provides some helpers for loading layer data manages maps and map objects.
*/
L.Contao = L.Class.extend({
includes: L.Mixin.Events,
statics: {
/**
* Contao extension attribution.
*
* You are not allowed to remove or change it. Contact me if you want to buy an removal license.
*/
ATTRIBUTION: ' | <a href="https://netzmacht.de/contao-leaflet" title="Powered by Leaflet extension for Contao CMS developed by netzmacht David Molineus">netzmacht</a>'
},
/**
* The map registry.
*/
maps: {},
/**
* The icons registry.
*/
icons: {},
/**
* Initialize Contao leaflet integration.
*/
initialize: function () {
L.Icon.Default.imagePath = 'assets/leaflet/libs/leaflet/images/';
this.setGeoJsonListeners(L.GeoJSON);
},
/**
* Add map to map registry.
*
* @param id The map id.
* @param map The map object.
*
* @returns {L.contao}
*/
addMap: function (id, map) {
this.maps[id] = map;
this.fire('map:added', {id: id, map: map});
return this;
},
/**
* Get a map from the icon map. Returns null if not set.
*
* @param id The mapobject
*
* @returns {L.Map}|{*}
*/
getMap: function (id) {
if (typeof (this.maps[id]) === 'undefined') {
return null;
}
return this.maps[id];
},
/**
* Add an icon to the icon registry.
*
* @param id The icon id.
* @param icon The icon object.
*
* @returns {L.contao}
*/
addIcon: function (id, icon) {
this.icons[id] = icon;
this.fire('icon:added', {id: id, icon: icon});
return this;
},
/**
* Load icon definitions.
*
* @param icons List of icon definitions.
*
* @return void
*/
loadIcons: function (icons) {
for (var i = 0; i < icons.length; i++) {
var icon;
if (icons[i].type === 'extraMarkers.icon') {
icon = L.ExtraMarkers.icon(icons[i].options);
} else {
icon = L[icons[i].type](icons[i].options);
}
this.addIcon(icons[i].id, icon);
}
},
/**
* Get an icon by its id.
*
* @param id Icon id.
*
* @returns {L.Icon}|{L.DivIcon}|{*}
*/
getIcon: function (id) {
if (typeof (this.icons[id]) === 'undefined') {
return null;
}
return this.icons[id];
},
/**
* Load data from an url into a layer using omnivore.
*
* @param hash The leaflet url hash.
* @param type The response content format.
* @param options Parser options
* @param customLayer optional custom layer.
* @param map Pass a map object so that the data loading events are passed to the map.
*/
load: function (hash, type, options, customLayer, map) {
var url = this.createRequestUrl(hash, map),
layer = omnivore[type](url, options, customLayer);
if (map) {
// Required because Control.Loading tries to get _leafet_id which is created here.
L.stamp(layer);
// Add listener for map bounds changes.
if (map.options.dynamicLoad && layer.options.boundsMode == 'fit') {
layer.options.requestHash = hash;
map.on('moveend', layer.refreshData, layer);
map.on('layerremove', function(e) {
if (e.layer === layer) {
map.off('moveend', layer.updateBounds, layer);
}
});
}
map.fire('dataloading', {layer: layer});
layer.on('ready', function () {
map.calculateFeatureBounds(layer);
map.fire('dataload', {layer: layer});
});
layer.on('error', function () {
map.fire('dataload', {layer: layer});
});
}
return layer;
},
/**
* Point to layer callback. Adds a geo json point to the layer.
*
* @param feature The geo json feature.
* @param latlng The converted latlng.
*
* @returns {L.Marker}|{*}
*/
pointToLayer: function (feature, latlng) {
var type = 'marker';
var marker = null;
if (feature.properties) {
feature.properties.bounds = true;
if (feature.properties.type) {
type = feature.properties.type;
}
// constructor arguments given, use them.
if (feature.properties.arguments) {
marker = L[type].apply(L[type], feature.properties.arguments);
L.Util.setOptions(marker, feature.properties.options);
}
}
if (marker === null) {
marker = L[type](latlng, feature.properties.options);
}
if (feature.properties) {
if (feature.properties.radius) {
marker.setRadius(feature.properties.radius);
}
if (feature.properties.icon) {
var icon = this.getIcon(feature.properties.icon);
if (icon) {
marker.setIcon(icon);
}
}
this.bindPopupFromFeature(marker, feature);
}
this.fire('point:added', {marker: marker, feature: feature, latlng: latlng, type: type});
return marker;
},
onEachFeature: function (feature, layer) {
if (feature.properties) {
L.Util.setOptions(layer, feature.properties.options);
this.bindPopupFromFeature(layer, feature);
this.fire('feature:added', {feature: feature, layer: layer});
}
},
/**
* Bind popup from feature definitions.
*
* It accepts popup or popupContent as property.
*
* @param obj The object
* @param feature The geo json feature.
*/
bindPopupFromFeature: function (obj, feature) {
if (feature.properties) {
if (feature.properties.popup) {
obj.bindPopup(feature.properties.popup, feature.properties.popupOptions);
} else if (feature.properties.popupContent) {
obj.bindPopup(feature.properties.popupContent, feature.properties.popupOptions);
}
}
},
/**
* Set the default geojson listeners to the prototype.
*
* @param obj
*/
setGeoJsonListeners: function (obj) {
if (obj && obj.prototype) {
obj.prototype.options = {
pointToLayer: this.pointToLayer.bind(this),
onEachFeature: this.onEachFeature.bind(this)
};
}
},
/**
* Create request url by appending the hash to the current url.
*
* @param {string} value The hash.
* @param {L.Map} map The map.
*
* @returns {string}
*/
createRequestUrl: function (value, map) {
var bounds,
key = 'leaflet',
params = document.location.search.substr(1).split('&');
value = encodeURIComponent(value);
if (params == '') {
value = document.location.pathname + '?' + [key, value].join('=');
} else {
var i = params.length;
var x;
while (i--) {
x = params[i].split('=');
if (x[0] == key) {
x[1] = value;
params[i] = x.join('=');
break;
}
}
if (i < 0) {
params[params.length] = [key, value].join('=');
}
value = document.location.pathname + '?' + params.join('&');
}
if (map) {
if (map.options.dynamicLoad) {
bounds = map.getBounds();
value += '&f=bbox&v=';
value += bounds.getSouth() + ',' + bounds.getWest();
value += ',' + bounds.getNorth() + ',' + bounds.getEast();
}
}
return value;
}
});
/**
* Start Contao integration.
*/
L.contao = new L.Contao();

19
js/Mixin.Attribution.js Normal file
View File

@@ -0,0 +1,19 @@
/**
* Attribution handling.
*/
L.Control.Attribution.addInitHook(function() {
this.options.prefix += L.Contao.ATTRIBUTION;
});
L.Control.Attribution.include({
setPrefix: function (prefix) {
if (prefix.indexOf(L.Contao.ATTRIBUTION) === -1) {
prefix += L.Contao.ATTRIBUTION;
}
this.options.prefix = prefix;
this._update();
return this;
}
});

34
js/Mixin.GeoJSON.js Normal file
View File

@@ -0,0 +1,34 @@
/**
* Add update bounds method for geo json layers. It is triggered when map bounds changed and make a new request
* to get the data in the new bounds.
*/
L.GeoJSON.include({
/**
* Update bounds.
*
* @param {L.Event} e The subscribed event.
*/
refreshData: function(e) {
var dataLayer = L.geoJson(),
layer = this;
dataLayer.on('ready', function() {
var i, layers = layer.getLayers();
// Clear old data.
for (i = 0; i < layers.length; i++) {
layer.removeLayer(layers[i]);
}
// Copy data from temporary layer.
layers = this.getLayers();
for (i = 0; i < layers.length; i++) {
this.removeLayer(layers[i]);
layer.addLayer(layers[i]);
}
});
// TODO: Allow other data formats.
omnivore.geojson(L.contao.createRequestUrl(this.options.requestHash, e.target), null, dataLayer);
}
});

103
js/Mixin.Map.js Normal file
View File

@@ -0,0 +1,103 @@
/**
* Extend map so that it can calculate their bounds depending of the features with the property boundsMode.
*/
L.Map.include({
_dynamicBounds: null,
/**
* Calculate feature bounds.
*
* Use this method without any arguments to scan the whole map for features.
*
* If a layer is passed then only this layer is used if the map option adjustBounds is set or the force flag
* is given.
*
* @param {L.Layer} layer Optional limit to a layer.
* @param {bool} force Force scaning of a layer no matter if adjustBounds is set.
*
* @return void
*/
calculateFeatureBounds: function(layer, force) {
if (layer) {
if (!this.options.adjustBounds && !force) {
return;
}
this._scanForBounds(layer);
} else {
this.eachLayer(this._scanForBounds, this);
}
if (this._dynamicBounds) {
this.fitBounds(this._dynamicBounds, this.getBoundsOptions());
}
},
/**
* Get the bounds optons
* @returns {{}}
*/
getBoundsOptions: function () {
options = {};
if (this.options.boundsPadding) {
options.padding = this.options.boundsPadding;
} else {
if (this.options.boundsPaddingTopLeft) {
options.paddingTopLeft = this.options.boundsPaddingTopLeft;
}
if (this.options.boundsPaddingBottomRight) {
options.paddingBottomRight = this.options.boundsPaddingBottomRight;
}
}
return options;
},
/**
* Scan recursively for bounds in a layer and extend _dynamicBounds if any found.
*
* @param {L.Layer} layer The layer
* @private
*/
_scanForBounds: function(layer) {
var source;
if (layer.feature && (!layer.feature.properties || !layer.feature.properties.ignoreForBounds)) {
if (layer.getBounds) {
source = layer.getBounds();
if (source.isValid()) {
if (this._dynamicBounds) {
this._dynamicBounds.extend(source);
} else {
this._dynamicBounds = L.latLngBounds(source.getSouthWest(), source.getNorthEast());
}
}
} else if (layer.getLatLng) {
source = layer.getLatLng();
if (this._dynamicBounds) {
this._dynamicBounds.extend(source);
} else {
this._dynamicBounds = L.latLngBounds(source, source);
}
}
} else if (L.MarkerClusterGroup && layer instanceof L.MarkerClusterGroup
&& layer.options.boundsMode && layer.options.boundsMode == 'extend') {
source = layer.getBounds();
if (source.isValid()) {
if (this._dynamicBounds) {
this._dynamicBounds.extend(source);
} else {
this._dynamicBounds = L.latLngBounds(source.getSouthWest(), source.getNorthEast());
}
}
} else if ((!layer.options || (layer.options
&& layer.options.boundsMode && !layer.options.ignoreForBounds)) && layer.eachLayer) {
layer.eachLayer(this._scanForBounds, this);
}
}
});

231
js/OverpassLayer.js Normal file
View File

@@ -0,0 +1,231 @@
/**
* Get the bounds as overpass bbox string.
*
* @returns {string}
*/
L.LatLngBounds.prototype.toOverpassBBoxString = function () {
var a = this._southWest,
b = this._northEast;
return [a.lat, a.lng, b.lat, b.lng].join(",");
};
/**
* Implementation of the overpass layer. Heavily inspired by
* https://github.com/kartenkarsten/leaflet-layer-overpass.
*/
L.OverPassLayer = L.FeatureGroup.extend({
options: {
minZoom: 0,
endpoint: '//overpass-api.de/api/',
query: '(node(BBOX)[organic];node(BBOX)[second_hand];);out qt;',
amenityIcons: {}
},
/**
* Initialize the layer.
*
* @param options
*/
initialize: function (options) {
if (!options.pointToLayer) {
options.pointToLayer = this.pointToLayer;
}
if (!options.onEachFeature) {
options.onEachFeature = this.onEachFeature;
}
L.Util.setOptions(this, options);
this.options.dynamicLoad = this.options.query.match(/BBOX/g) ? true : false;
this._layer = L.geoJson();
this._layers = {};
this.addLayer(this._layer);
},
/**
* Refresh the data of the layer.
*
* TODO: Implement some caching.
*/
refreshData: function () {
if (this._map.getZoom() < this.options.minZoom) {
return;
}
var bounds = this._map.getBounds().toOverpassBBoxString();
var query = this.options.query.replace(/(BBOX)/g, bounds);
var url = this.options.endpoint + "interpreter?data=[out:json];" + query;
this._map.fire('dataloading', {layer: this});
this.request(url, function (error, response) {
var data = JSON.parse(response.response);
var features = osmtogeojson(data);
var layer = L.geoJson(features, {
pointToLayer: this.options.pointToLayer.bind(this),
onEachFeature: this.options.onEachFeature.bind(this)
});
this.addLayer(layer);
this.removeLayer(this._layer);
this._layer = layer;
if (this.options.boundsMode === 'extend' && layer.getBounds().isValid()) {
var bounds = this._map.getBounds();
bounds = bounds.extend(layer.getBounds());
this._map.fitBounds(bounds, this._map.getBoundsOptions());
}
this._map.fire('dataload', {layer: this});
}.bind(this));
},
/**
* @param map
*/
onAdd: function (map) {
if (this.options.boundsMode === 'fit' && this.options.dynamicLoad) {
map.on('moveend', this.refreshData, this);
}
this.refreshData();
},
pointToLayer: function (feature, latlng) {
var type = 'marker';
var icon = null;
var marker = L.marker(latlng, feature.properties.options);
if (feature.properties) {
if (feature.properties.radius) {
marker.setRadius(feature.properties.radius);
}
if (feature.properties.icon) {
icon = this._map.getIcon(feature.properties.icon);
} else if (feature.properties.tags
&& feature.properties.tags.amenity
&& this.options.amenityIcons[feature.properties.tags.amenity]
) {
icon = L.contao.getIcon(this.options.amenityIcons[feature.properties.tags.amenity]);
}
if (icon) {
marker.setIcon(icon);
}
}
if (this.options.overpassPopup) {
marker.bindPopup(this.options.overpassPopup(feature, marker));
}
this._map.fire('point:added', {marker: marker, feature: feature, latlng: latlng, type: type});
return marker;
},
onEachFeature: function (feature, layer) {
if (feature.properties) {
L.Util.setOptions(layer, feature.properties.options);
if (this.options.overpassPopup) {
layer.bindPopup(this.options.overpassPopup(feature, layer));
}
this._map.fire('feature:added', {feature: feature, layer: layer});
}
},
/**
* Make an ajax request. Clone of corslite from MapQuest.
*/
request: function (url, callback, cors) {
var sent = false;
if (typeof window.XMLHttpRequest === 'undefined') {
return callback(Error('Browser not supported'));
}
if (typeof cors === 'undefined') {
var m = url.match(/^\s*https?:\/\/[^\/]*/);
cors = m && (m[0] !== location.protocol + '//' + location.hostname +
(location.port ? ':' + location.port : ''));
}
var x = new window.XMLHttpRequest();
function isSuccessful(status) {
return status >= 200 && status < 300 || status === 304;
}
if (cors && !('withCredentials' in x)) {
// IE8-9
x = new window.XDomainRequest();
// Ensure callback is never called synchronously, i.e., before
// x.send() returns (this has been observed in the wild).
// See https://github.com/mapbox/mapbox.js/issues/472
var original = callback;
callback = function() {
if (sent) {
original.apply(this, arguments);
} else {
var that = this, args = arguments;
setTimeout(function() {
original.apply(that, args);
}, 0);
}
}
}
function loaded() {
if (
// XDomainRequest
x.status === undefined ||
// modern browsers
isSuccessful(x.status)) callback.call(x, null, x);
else callback.call(x, x, null);
}
// Both `onreadystatechange` and `onload` can fire. `onreadystatechange`
// has [been supported for longer](http://stackoverflow.com/a/9181508/229001).
if ('onload' in x) {
x.onload = loaded;
} else {
x.onreadystatechange = function readystate() {
if (x.readyState === 4) {
loaded();
}
};
}
// Call the callback with the XMLHttpRequest object as an error and prevent
// it from ever being called again by reassigning it to `noop`
x.onerror = function error(evt) {
// XDomainRequest provides no evt parameter
callback.call(this, evt || true, null);
callback = function() { };
};
// IE9 must have onprogress be set to a unique function.
x.onprogress = function() { };
x.ontimeout = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
x.onabort = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
// GET is the only supported HTTP Verb by XDomainRequest and is the
// only one supported here.
x.open('GET', url, true);
// Send the request. Sending data is not supported.
x.send(null);
sent = true;
return x;
}
});