Initial commit
This commit is contained in:
@@ -0,0 +1,304 @@
|
||||
L.interpolatePosition = function(p1, p2, duration, t) {
|
||||
var k = t/duration;
|
||||
k = (k > 0) ? k : 0;
|
||||
k = (k > 1) ? 1 : k;
|
||||
return L.latLng(p1.lat + k * (p2.lat - p1.lat),
|
||||
p1.lng + k * (p2.lng - p1.lng));
|
||||
};
|
||||
|
||||
L.Marker.MovingMarker = L.Marker.extend({
|
||||
|
||||
//state constants
|
||||
statics: {
|
||||
notStartedState: 0,
|
||||
endedState: 1,
|
||||
pausedState: 2,
|
||||
runState: 3
|
||||
},
|
||||
|
||||
options: {
|
||||
autostart: false,
|
||||
loop: false,
|
||||
},
|
||||
|
||||
initialize: function (latlngs, durations, options) {
|
||||
L.Marker.prototype.initialize.call(this, latlngs[0], options);
|
||||
|
||||
this._latlngs = latlngs.map(function(e, index) {
|
||||
return L.latLng(e);
|
||||
});
|
||||
|
||||
if (durations instanceof Array) {
|
||||
this._durations = durations;
|
||||
} else {
|
||||
this._durations = this._createDurations(this._latlngs, durations);
|
||||
}
|
||||
|
||||
this._currentDuration = 0;
|
||||
this._currentIndex = 0;
|
||||
|
||||
this._state = L.Marker.MovingMarker.notStartedState;
|
||||
this._startTime = 0;
|
||||
this._startTimeStamp = 0; // timestamp given by requestAnimFrame
|
||||
this._pauseStartTime = 0;
|
||||
this._animId = 0;
|
||||
this._animRequested = false;
|
||||
this._currentLine = [];
|
||||
this._stations = {};
|
||||
},
|
||||
|
||||
isRunning: function() {
|
||||
return this._state === L.Marker.MovingMarker.runState;
|
||||
},
|
||||
|
||||
isEnded: function() {
|
||||
return this._state === L.Marker.MovingMarker.endedState;
|
||||
},
|
||||
|
||||
isStarted: function() {
|
||||
return this._state !== L.Marker.MovingMarker.notStartedState;
|
||||
},
|
||||
|
||||
isPaused: function() {
|
||||
return this._state === L.Marker.MovingMarker.pausedState;
|
||||
},
|
||||
|
||||
start: function() {
|
||||
if (this.isRunning()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isPaused()) {
|
||||
this.resume();
|
||||
} else {
|
||||
this._loadLine(0);
|
||||
this._startAnimation();
|
||||
this.fire('start');
|
||||
}
|
||||
},
|
||||
|
||||
resume: function() {
|
||||
if (! this.isPaused()) {
|
||||
return;
|
||||
}
|
||||
// update the current line
|
||||
this._currentLine[0] = this.getLatLng();
|
||||
this._currentDuration -= (this._pauseStartTime - this._startTime);
|
||||
this._startAnimation();
|
||||
},
|
||||
|
||||
pause: function() {
|
||||
if (! this.isRunning()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._pauseStartTime = Date.now();
|
||||
this._state = L.Marker.MovingMarker.pausedState;
|
||||
this._stopAnimation();
|
||||
this._updatePosition();
|
||||
},
|
||||
|
||||
stop: function(elapsedTime) {
|
||||
if (this.isEnded()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._stopAnimation();
|
||||
|
||||
if (typeof(elapsedTime) === 'undefined') {
|
||||
// user call
|
||||
elapsedTime = 0;
|
||||
this._updatePosition();
|
||||
}
|
||||
|
||||
this._state = L.Marker.MovingMarker.endedState;
|
||||
this.fire('end', {elapsedTime: elapsedTime});
|
||||
},
|
||||
|
||||
addLatLng: function(latlng, duration) {
|
||||
this._latlngs.push(L.latLng(latlng));
|
||||
this._durations.push(duration);
|
||||
},
|
||||
|
||||
moveTo: function(latlng, duration) {
|
||||
this._stopAnimation();
|
||||
this._latlngs = [this.getLatLng(), L.latLng(latlng)];
|
||||
this._durations = [duration];
|
||||
this._state = L.Marker.MovingMarker.notStartedState;
|
||||
this.start();
|
||||
this.options.loop = false;
|
||||
},
|
||||
|
||||
addStation: function(pointIndex, duration) {
|
||||
if (pointIndex > this._latlngs.length - 2 || pointIndex < 1) {
|
||||
return;
|
||||
}
|
||||
this._stations[pointIndex] = duration;
|
||||
},
|
||||
|
||||
onAdd: function (map) {
|
||||
L.Marker.prototype.onAdd.call(this, map);
|
||||
|
||||
if (this.options.autostart && (! this.isStarted())) {
|
||||
this.start();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isRunning()) {
|
||||
this._resumeAnimation();
|
||||
}
|
||||
},
|
||||
|
||||
onRemove: function(map) {
|
||||
L.Marker.prototype.onRemove.call(this, map);
|
||||
this._stopAnimation();
|
||||
},
|
||||
|
||||
_createDurations: function (latlngs, duration) {
|
||||
var lastIndex = latlngs.length - 1;
|
||||
var distances = [];
|
||||
var totalDistance = 0;
|
||||
var distance = 0;
|
||||
|
||||
// compute array of distances between points
|
||||
for (var i = 0; i < lastIndex; i++) {
|
||||
distance = latlngs[i + 1].distanceTo(latlngs[i]);
|
||||
distances.push(distance);
|
||||
totalDistance += distance;
|
||||
}
|
||||
|
||||
var ratioDuration = duration / totalDistance;
|
||||
|
||||
var durations = [];
|
||||
for (i = 0; i < distances.length; i++) {
|
||||
durations.push(distances[i] * ratioDuration);
|
||||
}
|
||||
|
||||
return durations;
|
||||
},
|
||||
|
||||
_startAnimation: function() {
|
||||
this._state = L.Marker.MovingMarker.runState;
|
||||
this._animId = L.Util.requestAnimFrame(function(timestamp) {
|
||||
this._startTime = Date.now();
|
||||
this._startTimeStamp = timestamp;
|
||||
this._animate(timestamp);
|
||||
}, this, true);
|
||||
this._animRequested = true;
|
||||
},
|
||||
|
||||
_resumeAnimation: function() {
|
||||
if (! this._animRequested) {
|
||||
this._animRequested = true;
|
||||
this._animId = L.Util.requestAnimFrame(function(timestamp) {
|
||||
this._animate(timestamp);
|
||||
}, this, true);
|
||||
}
|
||||
},
|
||||
|
||||
_stopAnimation: function() {
|
||||
if (this._animRequested) {
|
||||
L.Util.cancelAnimFrame(this._animId);
|
||||
this._animRequested = false;
|
||||
}
|
||||
},
|
||||
|
||||
_updatePosition: function() {
|
||||
var elapsedTime = Date.now() - this._startTime;
|
||||
this._animate(this._startTimeStamp + elapsedTime, true);
|
||||
},
|
||||
|
||||
_loadLine: function(index) {
|
||||
this._currentIndex = index;
|
||||
this._currentDuration = this._durations[index];
|
||||
this._currentLine = this._latlngs.slice(index, index + 2);
|
||||
},
|
||||
|
||||
/**
|
||||
* Load the line where the marker is
|
||||
* @param {Number} timestamp
|
||||
* @return {Number} elapsed time on the current line or null if
|
||||
* we reached the end or marker is at a station
|
||||
*/
|
||||
_updateLine: function(timestamp) {
|
||||
// time elapsed since the last latlng
|
||||
var elapsedTime = timestamp - this._startTimeStamp;
|
||||
|
||||
// not enough time to update the line
|
||||
if (elapsedTime <= this._currentDuration) {
|
||||
return elapsedTime;
|
||||
}
|
||||
|
||||
var lineIndex = this._currentIndex;
|
||||
var lineDuration = this._currentDuration;
|
||||
var stationDuration;
|
||||
|
||||
while (elapsedTime > lineDuration) {
|
||||
// substract time of the current line
|
||||
elapsedTime -= lineDuration;
|
||||
stationDuration = this._stations[lineIndex + 1];
|
||||
|
||||
// test if there is a station at the end of the line
|
||||
if (stationDuration !== undefined) {
|
||||
if (elapsedTime < stationDuration) {
|
||||
this.setLatLng(this._latlngs[lineIndex + 1]);
|
||||
return null;
|
||||
}
|
||||
elapsedTime -= stationDuration;
|
||||
}
|
||||
|
||||
lineIndex++;
|
||||
|
||||
// test if we have reached the end of the polyline
|
||||
if (lineIndex >= this._latlngs.length - 1) {
|
||||
|
||||
if (this.options.loop) {
|
||||
lineIndex = 0;
|
||||
this.fire('loop', {elapsedTime: elapsedTime});
|
||||
} else {
|
||||
// place the marker at the end, else it would be at
|
||||
// the last position
|
||||
this.setLatLng(this._latlngs[this._latlngs.length - 1]);
|
||||
this.stop(elapsedTime);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
lineDuration = this._durations[lineIndex];
|
||||
}
|
||||
|
||||
this._loadLine(lineIndex);
|
||||
this._startTimeStamp = timestamp - elapsedTime;
|
||||
this._startTime = Date.now() - elapsedTime;
|
||||
return elapsedTime;
|
||||
},
|
||||
|
||||
_animate: function(timestamp, noRequestAnim) {
|
||||
this._animRequested = false;
|
||||
|
||||
// find the next line and compute the new elapsedTime
|
||||
var elapsedTime = this._updateLine(timestamp);
|
||||
|
||||
if (this.isEnded()) {
|
||||
// no need to animate
|
||||
return;
|
||||
}
|
||||
|
||||
if (elapsedTime != null) {
|
||||
// compute the position
|
||||
var p = L.interpolatePosition(this._currentLine[0],
|
||||
this._currentLine[1],
|
||||
this._currentDuration,
|
||||
elapsedTime);
|
||||
this.setLatLng(p);
|
||||
}
|
||||
|
||||
if (! noRequestAnim) {
|
||||
this._animId = L.Util.requestAnimFrame(this._animate, this, false);
|
||||
this._animRequested = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
L.Marker.movingMarker = function (latlngs, duration, options) {
|
||||
return new L.Marker.MovingMarker(latlngs, duration, options);
|
||||
};
|
||||
Vendored
+2
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,767 @@
|
||||
// Packaging/modules magic dance.
|
||||
(function (factory) {
|
||||
var L;
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
// AMD
|
||||
define(['leaflet'], factory);
|
||||
} else if (typeof module !== 'undefined') {
|
||||
// Node/CommonJS
|
||||
L = require('leaflet');
|
||||
module.exports = factory(L);
|
||||
} else {
|
||||
// Browser globals
|
||||
if (typeof window.L === 'undefined')
|
||||
throw 'Leaflet must be loaded first';
|
||||
factory(window.L);
|
||||
}
|
||||
}(function (L) {
|
||||
"use strict";
|
||||
|
||||
L.Polyline._flat = L.LineUtil.isFlat || L.Polyline._flat || function (latlngs) {
|
||||
// true if it's a flat array of latlngs; false if nested
|
||||
return !L.Util.isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileOverview Leaflet Geometry utilities for distances and linear referencing.
|
||||
* @name L.GeometryUtil
|
||||
*/
|
||||
|
||||
L.GeometryUtil = L.extend(L.GeometryUtil || {}, {
|
||||
|
||||
/**
|
||||
Shortcut function for planar distance between two {L.LatLng} at current zoom.
|
||||
|
||||
@tutorial distance-length
|
||||
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {L.LatLng} latlngA geographical point A
|
||||
@param {L.LatLng} latlngB geographical point B
|
||||
@returns {Number} planar distance
|
||||
*/
|
||||
distance: function (map, latlngA, latlngB) {
|
||||
return map.latLngToLayerPoint(latlngA).distanceTo(map.latLngToLayerPoint(latlngB));
|
||||
},
|
||||
|
||||
/**
|
||||
Shortcut function for planar distance between a {L.LatLng} and a segment (A-B).
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {L.LatLng} latlng - The position to search
|
||||
@param {L.LatLng} latlngA geographical point A of the segment
|
||||
@param {L.LatLng} latlngB geographical point B of the segment
|
||||
@returns {Number} planar distance
|
||||
*/
|
||||
distanceSegment: function (map, latlng, latlngA, latlngB) {
|
||||
var p = map.latLngToLayerPoint(latlng),
|
||||
p1 = map.latLngToLayerPoint(latlngA),
|
||||
p2 = map.latLngToLayerPoint(latlngB);
|
||||
return L.LineUtil.pointToSegmentDistance(p, p1, p2);
|
||||
},
|
||||
|
||||
/**
|
||||
Shortcut function for converting distance to readable distance.
|
||||
@param {Number} distance distance to be converted
|
||||
@param {String} unit 'metric' or 'imperial'
|
||||
@returns {String} in yard or miles
|
||||
*/
|
||||
readableDistance: function (distance, unit) {
|
||||
var isMetric = (unit !== 'imperial'),
|
||||
distanceStr;
|
||||
if (isMetric) {
|
||||
// show metres when distance is < 1km, then show km
|
||||
if (distance > 1000) {
|
||||
distanceStr = (distance / 1000).toFixed(2) + ' km';
|
||||
}
|
||||
else {
|
||||
distanceStr = Math.ceil(distance) + ' m';
|
||||
}
|
||||
}
|
||||
else {
|
||||
distance *= 1.09361;
|
||||
if (distance > 1760) {
|
||||
distanceStr = (distance / 1760).toFixed(2) + ' miles';
|
||||
}
|
||||
else {
|
||||
distanceStr = Math.ceil(distance) + ' yd';
|
||||
}
|
||||
}
|
||||
return distanceStr;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns true if the latlng belongs to segment A-B
|
||||
@param {L.LatLng} latlng - The position to search
|
||||
@param {L.LatLng} latlngA geographical point A of the segment
|
||||
@param {L.LatLng} latlngB geographical point B of the segment
|
||||
@param {?Number} [tolerance=0.2] tolerance to accept if latlng belongs really
|
||||
@returns {boolean}
|
||||
*/
|
||||
belongsSegment: function(latlng, latlngA, latlngB, tolerance) {
|
||||
tolerance = tolerance === undefined ? 0.2 : tolerance;
|
||||
var hypotenuse = latlngA.distanceTo(latlngB),
|
||||
delta = latlngA.distanceTo(latlng) + latlng.distanceTo(latlngB) - hypotenuse;
|
||||
return delta/hypotenuse < tolerance;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns total length of line
|
||||
* @tutorial distance-length
|
||||
*
|
||||
* @param {L.Polyline|Array<L.Point>|Array<L.LatLng>} coords Set of coordinates
|
||||
* @returns {Number} Total length (pixels for Point, meters for LatLng)
|
||||
*/
|
||||
length: function (coords) {
|
||||
var accumulated = L.GeometryUtil.accumulatedLengths(coords);
|
||||
return accumulated.length > 0 ? accumulated[accumulated.length-1] : 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a list of accumulated length along a line.
|
||||
* @param {L.Polyline|Array<L.Point>|Array<L.LatLng>} coords Set of coordinates
|
||||
* @returns {Array<Number>} Array of accumulated lengths (pixels for Point, meters for LatLng)
|
||||
*/
|
||||
accumulatedLengths: function (coords) {
|
||||
if (typeof coords.getLatLngs == 'function') {
|
||||
coords = coords.getLatLngs();
|
||||
}
|
||||
if (coords.length === 0)
|
||||
return [];
|
||||
var total = 0,
|
||||
lengths = [0];
|
||||
for (var i = 0, n = coords.length - 1; i< n; i++) {
|
||||
total += coords[i].distanceTo(coords[i+1]);
|
||||
lengths.push(total);
|
||||
}
|
||||
return lengths;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the closest point of a {L.LatLng} on the segment (A-B)
|
||||
|
||||
@tutorial closest
|
||||
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {L.LatLng} latlng - The position to search
|
||||
@param {L.LatLng} latlngA geographical point A of the segment
|
||||
@param {L.LatLng} latlngB geographical point B of the segment
|
||||
@returns {L.LatLng} Closest geographical point
|
||||
*/
|
||||
closestOnSegment: function (map, latlng, latlngA, latlngB) {
|
||||
var maxzoom = map.getMaxZoom();
|
||||
if (maxzoom === Infinity)
|
||||
maxzoom = map.getZoom();
|
||||
var p = map.project(latlng, maxzoom),
|
||||
p1 = map.project(latlngA, maxzoom),
|
||||
p2 = map.project(latlngB, maxzoom),
|
||||
closest = L.LineUtil.closestPointOnSegment(p, p1, p2);
|
||||
return map.unproject(closest, maxzoom);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the closest latlng on layer.
|
||||
|
||||
Accept nested arrays
|
||||
|
||||
@tutorial closest
|
||||
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {Array<L.LatLng>|Array<Array<L.LatLng>>|L.PolyLine|L.Polygon} layer - Layer that contains the result
|
||||
@param {L.LatLng} latlng - The position to search
|
||||
@param {?boolean} [vertices=false] - Whether to restrict to path vertices.
|
||||
@returns {L.LatLng} Closest geographical point or null if layer param is incorrect
|
||||
*/
|
||||
closest: function (map, layer, latlng, vertices) {
|
||||
|
||||
var latlngs,
|
||||
mindist = Infinity,
|
||||
result = null,
|
||||
i, n, distance, subResult;
|
||||
|
||||
if (layer instanceof Array) {
|
||||
// if layer is Array<Array<T>>
|
||||
if (layer[0] instanceof Array && typeof layer[0][0] !== 'number') {
|
||||
// if we have nested arrays, we calc the closest for each array
|
||||
// recursive
|
||||
for (i = 0; i < layer.length; i++) {
|
||||
subResult = L.GeometryUtil.closest(map, layer[i], latlng, vertices);
|
||||
if (subResult.distance < mindist) {
|
||||
mindist = subResult.distance;
|
||||
result = subResult;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} else if (layer[0] instanceof L.LatLng
|
||||
|| typeof layer[0][0] === 'number'
|
||||
|| typeof layer[0].lat === 'number') { // we could have a latlng as [x,y] with x & y numbers or {lat, lng}
|
||||
layer = L.polyline(layer);
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// if we don't have here a Polyline, that means layer is incorrect
|
||||
// see https://github.com/makinacorpus/Leaflet.GeometryUtil/issues/23
|
||||
if (! ( layer instanceof L.Polyline ) )
|
||||
return result;
|
||||
|
||||
// deep copy of latlngs
|
||||
latlngs = JSON.parse(JSON.stringify(layer.getLatLngs().slice(0)));
|
||||
|
||||
// add the last segment for L.Polygon
|
||||
if (layer instanceof L.Polygon) {
|
||||
// add the last segment for each child that is a nested array
|
||||
var addLastSegment = function(latlngs) {
|
||||
if (L.Polyline._flat(latlngs)) {
|
||||
latlngs.push(latlngs[0]);
|
||||
} else {
|
||||
for (var i = 0; i < latlngs.length; i++) {
|
||||
addLastSegment(latlngs[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
addLastSegment(latlngs);
|
||||
}
|
||||
|
||||
// we have a multi polygon / multi polyline / polygon with holes
|
||||
// use recursive to explore and return the good result
|
||||
if ( ! L.Polyline._flat(latlngs) ) {
|
||||
for (i = 0; i < latlngs.length; i++) {
|
||||
// if we are at the lower level, and if we have a L.Polygon, we add the last segment
|
||||
subResult = L.GeometryUtil.closest(map, latlngs[i], latlng, vertices);
|
||||
if (subResult.distance < mindist) {
|
||||
mindist = subResult.distance;
|
||||
result = subResult;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
|
||||
} else {
|
||||
|
||||
// Lookup vertices
|
||||
if (vertices) {
|
||||
for(i = 0, n = latlngs.length; i < n; i++) {
|
||||
var ll = latlngs[i];
|
||||
distance = L.GeometryUtil.distance(map, latlng, ll);
|
||||
if (distance < mindist) {
|
||||
mindist = distance;
|
||||
result = ll;
|
||||
result.distance = distance;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Keep the closest point of all segments
|
||||
for (i = 0, n = latlngs.length; i < n-1; i++) {
|
||||
var latlngA = latlngs[i],
|
||||
latlngB = latlngs[i+1];
|
||||
distance = L.GeometryUtil.distanceSegment(map, latlng, latlngA, latlngB);
|
||||
if (distance <= mindist) {
|
||||
mindist = distance;
|
||||
result = L.GeometryUtil.closestOnSegment(map, latlng, latlngA, latlngB);
|
||||
result.distance = distance;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the closest layer to latlng among a list of layers.
|
||||
|
||||
@tutorial closest
|
||||
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {Array<L.ILayer>} layers Set of layers
|
||||
@param {L.LatLng} latlng - The position to search
|
||||
@returns {object} ``{layer, latlng, distance}`` or ``null`` if list is empty;
|
||||
*/
|
||||
closestLayer: function (map, layers, latlng) {
|
||||
var mindist = Infinity,
|
||||
result = null,
|
||||
ll = null,
|
||||
distance = Infinity;
|
||||
|
||||
for (var i = 0, n = layers.length; i < n; i++) {
|
||||
var layer = layers[i];
|
||||
if (layer instanceof L.LayerGroup) {
|
||||
// recursive
|
||||
var subResult = L.GeometryUtil.closestLayer(map, layer.getLayers(), latlng);
|
||||
if (subResult.distance < mindist) {
|
||||
mindist = subResult.distance;
|
||||
result = subResult;
|
||||
}
|
||||
} else {
|
||||
// Single dimension, snap on points, else snap on closest
|
||||
if (typeof layer.getLatLng == 'function') {
|
||||
ll = layer.getLatLng();
|
||||
distance = L.GeometryUtil.distance(map, latlng, ll);
|
||||
}
|
||||
else {
|
||||
ll = L.GeometryUtil.closest(map, layer, latlng);
|
||||
if (ll) distance = ll.distance; // Can return null if layer has no points.
|
||||
}
|
||||
if (distance < mindist) {
|
||||
mindist = distance;
|
||||
result = {layer: layer, latlng: ll, distance: distance};
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the n closest layers to latlng among a list of input layers.
|
||||
|
||||
@param {L.Map} map - Leaflet map to be used for this method
|
||||
@param {Array<L.ILayer>} layers - Set of layers
|
||||
@param {L.LatLng} latlng - The position to search
|
||||
@param {?Number} [n=layers.length] - the expected number of output layers.
|
||||
@returns {Array<object>} an array of objects ``{layer, latlng, distance}`` or ``null`` if the input is invalid (empty list or negative n)
|
||||
*/
|
||||
nClosestLayers: function (map, layers, latlng, n) {
|
||||
n = typeof n === 'number' ? n : layers.length;
|
||||
|
||||
if (n < 1 || layers.length < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var results = [];
|
||||
var distance, ll;
|
||||
|
||||
for (var i = 0, m = layers.length; i < m; i++) {
|
||||
var layer = layers[i];
|
||||
if (layer instanceof L.LayerGroup) {
|
||||
// recursive
|
||||
var subResult = L.GeometryUtil.closestLayer(map, layer.getLayers(), latlng);
|
||||
results.push(subResult);
|
||||
} else {
|
||||
// Single dimension, snap on points, else snap on closest
|
||||
if (typeof layer.getLatLng == 'function') {
|
||||
ll = layer.getLatLng();
|
||||
distance = L.GeometryUtil.distance(map, latlng, ll);
|
||||
}
|
||||
else {
|
||||
ll = L.GeometryUtil.closest(map, layer, latlng);
|
||||
if (ll) distance = ll.distance; // Can return null if layer has no points.
|
||||
}
|
||||
results.push({layer: layer, latlng: ll, distance: distance});
|
||||
}
|
||||
}
|
||||
|
||||
results.sort(function(a, b) {
|
||||
return a.distance - b.distance;
|
||||
});
|
||||
|
||||
if (results.length > n) {
|
||||
return results.slice(0, n);
|
||||
} else {
|
||||
return results;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns all layers within a radius of the given position, in an ascending order of distance.
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {Array<ILayer>} layers - A list of layers.
|
||||
@param {L.LatLng} latlng - The position to search
|
||||
@param {?Number} [radius=Infinity] - Search radius in pixels
|
||||
@return {object[]} an array of objects including layer within the radius, closest latlng, and distance
|
||||
*/
|
||||
layersWithin: function(map, layers, latlng, radius) {
|
||||
radius = typeof radius == 'number' ? radius : Infinity;
|
||||
|
||||
var results = [];
|
||||
var ll = null;
|
||||
var distance = 0;
|
||||
|
||||
for (var i = 0, n = layers.length; i < n; i++) {
|
||||
var layer = layers[i];
|
||||
|
||||
if (typeof layer.getLatLng == 'function') {
|
||||
ll = layer.getLatLng();
|
||||
distance = L.GeometryUtil.distance(map, latlng, ll);
|
||||
}
|
||||
else {
|
||||
ll = L.GeometryUtil.closest(map, layer, latlng);
|
||||
if (ll) distance = ll.distance; // Can return null if layer has no points.
|
||||
}
|
||||
|
||||
if (ll && distance < radius) {
|
||||
results.push({layer: layer, latlng: ll, distance: distance});
|
||||
}
|
||||
}
|
||||
|
||||
var sortedResults = results.sort(function(a, b) {
|
||||
return a.distance - b.distance;
|
||||
});
|
||||
|
||||
return sortedResults;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the closest position from specified {LatLng} among specified layers,
|
||||
with a maximum tolerance in pixels, providing snapping behaviour.
|
||||
|
||||
@tutorial closest
|
||||
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {Array<ILayer>} layers - A list of layers to snap on.
|
||||
@param {L.LatLng} latlng - The position to snap
|
||||
@param {?Number} [tolerance=Infinity] - Maximum number of pixels.
|
||||
@param {?boolean} [withVertices=true] - Snap to layers vertices or segment points (not only vertex)
|
||||
@returns {object} with snapped {LatLng} and snapped {Layer} or null if tolerance exceeded.
|
||||
*/
|
||||
closestLayerSnap: function (map, layers, latlng, tolerance, withVertices) {
|
||||
tolerance = typeof tolerance == 'number' ? tolerance : Infinity;
|
||||
withVertices = typeof withVertices == 'boolean' ? withVertices : true;
|
||||
|
||||
var result = L.GeometryUtil.closestLayer(map, layers, latlng);
|
||||
if (!result || result.distance > tolerance)
|
||||
return null;
|
||||
|
||||
// If snapped layer is linear, try to snap on vertices (extremities and middle points)
|
||||
if (withVertices && typeof result.layer.getLatLngs == 'function') {
|
||||
var closest = L.GeometryUtil.closest(map, result.layer, result.latlng, true);
|
||||
if (closest.distance < tolerance) {
|
||||
result.latlng = closest;
|
||||
result.distance = L.GeometryUtil.distance(map, closest, latlng);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the Point located on a segment at the specified ratio of the segment length.
|
||||
@param {L.Point} pA coordinates of point A
|
||||
@param {L.Point} pB coordinates of point B
|
||||
@param {Number} the length ratio, expressed as a decimal between 0 and 1, inclusive.
|
||||
@returns {L.Point} the interpolated point.
|
||||
*/
|
||||
interpolateOnPointSegment: function (pA, pB, ratio) {
|
||||
return L.point(
|
||||
(pA.x * (1 - ratio)) + (ratio * pB.x),
|
||||
(pA.y * (1 - ratio)) + (ratio * pB.y)
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the coordinate of the point located on a line at the specified ratio of the line length.
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {Array<L.LatLng>|L.PolyLine} latlngs Set of geographical points
|
||||
@param {Number} ratio the length ratio, expressed as a decimal between 0 and 1, inclusive
|
||||
@returns {Object} an object with latLng ({LatLng}) and predecessor ({Number}), the index of the preceding vertex in the Polyline
|
||||
(-1 if the interpolated point is the first vertex)
|
||||
*/
|
||||
interpolateOnLine: function (map, latLngs, ratio) {
|
||||
latLngs = (latLngs instanceof L.Polyline) ? latLngs.getLatLngs() : latLngs;
|
||||
var n = latLngs.length;
|
||||
if (n < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ensure the ratio is between 0 and 1;
|
||||
ratio = Math.max(Math.min(ratio, 1), 0);
|
||||
|
||||
if (ratio === 0) {
|
||||
return {
|
||||
latLng: latLngs[0] instanceof L.LatLng ? latLngs[0] : L.latLng(latLngs[0]),
|
||||
predecessor: -1
|
||||
};
|
||||
}
|
||||
if (ratio == 1) {
|
||||
return {
|
||||
latLng: latLngs[latLngs.length -1] instanceof L.LatLng ? latLngs[latLngs.length -1] : L.latLng(latLngs[latLngs.length -1]),
|
||||
predecessor: latLngs.length - 2
|
||||
};
|
||||
}
|
||||
|
||||
// project the LatLngs as Points,
|
||||
// and compute total planar length of the line at max precision
|
||||
var maxzoom = map.getMaxZoom();
|
||||
if (maxzoom === Infinity)
|
||||
maxzoom = map.getZoom();
|
||||
var pts = [];
|
||||
var lineLength = 0;
|
||||
for(var i = 0; i < n; i++) {
|
||||
pts[i] = map.project(latLngs[i], maxzoom);
|
||||
if(i > 0)
|
||||
lineLength += pts[i-1].distanceTo(pts[i]);
|
||||
}
|
||||
|
||||
var ratioDist = lineLength * ratio;
|
||||
|
||||
// follow the line segments [ab], adding lengths,
|
||||
// until we find the segment where the points should lie on
|
||||
var cumulativeDistanceToA = 0, cumulativeDistanceToB = 0;
|
||||
for (var i = 0; cumulativeDistanceToB < ratioDist; i++) {
|
||||
var pointA = pts[i], pointB = pts[i+1];
|
||||
|
||||
cumulativeDistanceToA = cumulativeDistanceToB;
|
||||
cumulativeDistanceToB += pointA.distanceTo(pointB);
|
||||
}
|
||||
|
||||
if (pointA == undefined && pointB == undefined) { // Happens when line has no length
|
||||
var pointA = pts[0], pointB = pts[1], i = 1;
|
||||
}
|
||||
|
||||
// compute the ratio relative to the segment [ab]
|
||||
var segmentRatio = ((cumulativeDistanceToB - cumulativeDistanceToA) !== 0) ? ((ratioDist - cumulativeDistanceToA) / (cumulativeDistanceToB - cumulativeDistanceToA)) : 0;
|
||||
var interpolatedPoint = L.GeometryUtil.interpolateOnPointSegment(pointA, pointB, segmentRatio);
|
||||
return {
|
||||
latLng: map.unproject(interpolatedPoint, maxzoom),
|
||||
predecessor: i-1
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
Returns a float between 0 and 1 representing the location of the
|
||||
closest point on polyline to the given latlng, as a fraction of total line length.
|
||||
(opposite of L.GeometryUtil.interpolateOnLine())
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {L.PolyLine} polyline Polyline on which the latlng will be search
|
||||
@param {L.LatLng} latlng The position to search
|
||||
@returns {Number} Float between 0 and 1
|
||||
*/
|
||||
locateOnLine: function (map, polyline, latlng) {
|
||||
var latlngs = polyline.getLatLngs();
|
||||
if (latlng.equals(latlngs[0]))
|
||||
return 0.0;
|
||||
if (latlng.equals(latlngs[latlngs.length-1]))
|
||||
return 1.0;
|
||||
|
||||
var point = L.GeometryUtil.closest(map, polyline, latlng, false),
|
||||
lengths = L.GeometryUtil.accumulatedLengths(latlngs),
|
||||
total_length = lengths[lengths.length-1],
|
||||
portion = 0,
|
||||
found = false;
|
||||
for (var i=0, n = latlngs.length-1; i < n; i++) {
|
||||
var l1 = latlngs[i],
|
||||
l2 = latlngs[i+1];
|
||||
portion = lengths[i];
|
||||
if (L.GeometryUtil.belongsSegment(point, l1, l2, 0.0001)) {
|
||||
portion += l1.distanceTo(point);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
throw "Could not interpolate " + latlng.toString() + " within " + polyline.toString();
|
||||
}
|
||||
return portion / total_length;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns a clone with reversed coordinates.
|
||||
@param {L.PolyLine} polyline polyline to reverse
|
||||
@returns {L.PolyLine} polyline reversed
|
||||
*/
|
||||
reverse: function (polyline) {
|
||||
return L.polyline(polyline.getLatLngs().slice(0).reverse());
|
||||
},
|
||||
|
||||
/**
|
||||
Returns a sub-part of the polyline, from start to end.
|
||||
If start is superior to end, returns extraction from inverted line.
|
||||
@param {L.Map} map Leaflet map to be used for this method
|
||||
@param {L.PolyLine} polyline Polyline on which will be extracted the sub-part
|
||||
@param {Number} start ratio, expressed as a decimal between 0 and 1, inclusive
|
||||
@param {Number} end ratio, expressed as a decimal between 0 and 1, inclusive
|
||||
@returns {Array<L.LatLng>} new polyline
|
||||
*/
|
||||
extract: function (map, polyline, start, end) {
|
||||
if (start > end) {
|
||||
return L.GeometryUtil.extract(map, L.GeometryUtil.reverse(polyline), 1.0-start, 1.0-end);
|
||||
}
|
||||
|
||||
// Bound start and end to [0-1]
|
||||
start = Math.max(Math.min(start, 1), 0);
|
||||
end = Math.max(Math.min(end, 1), 0);
|
||||
|
||||
var latlngs = polyline.getLatLngs(),
|
||||
startpoint = L.GeometryUtil.interpolateOnLine(map, polyline, start),
|
||||
endpoint = L.GeometryUtil.interpolateOnLine(map, polyline, end);
|
||||
// Return single point if start == end
|
||||
if (start == end) {
|
||||
var point = L.GeometryUtil.interpolateOnLine(map, polyline, end);
|
||||
return [point.latLng];
|
||||
}
|
||||
// Array.slice() works indexes at 0
|
||||
if (startpoint.predecessor == -1)
|
||||
startpoint.predecessor = 0;
|
||||
if (endpoint.predecessor == -1)
|
||||
endpoint.predecessor = 0;
|
||||
var result = latlngs.slice(startpoint.predecessor+1, endpoint.predecessor+1);
|
||||
result.unshift(startpoint.latLng);
|
||||
result.push(endpoint.latLng);
|
||||
return result;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns true if first polyline ends where other second starts.
|
||||
@param {L.PolyLine} polyline First polyline
|
||||
@param {L.PolyLine} other Second polyline
|
||||
@returns {bool}
|
||||
*/
|
||||
isBefore: function (polyline, other) {
|
||||
if (!other) return false;
|
||||
var lla = polyline.getLatLngs(),
|
||||
llb = other.getLatLngs();
|
||||
return (lla[lla.length-1]).equals(llb[0]);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns true if first polyline starts where second ends.
|
||||
@param {L.PolyLine} polyline First polyline
|
||||
@param {L.PolyLine} other Second polyline
|
||||
@returns {bool}
|
||||
*/
|
||||
isAfter: function (polyline, other) {
|
||||
if (!other) return false;
|
||||
var lla = polyline.getLatLngs(),
|
||||
llb = other.getLatLngs();
|
||||
return (lla[0]).equals(llb[llb.length-1]);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns true if first polyline starts where second ends or start.
|
||||
@param {L.PolyLine} polyline First polyline
|
||||
@param {L.PolyLine} other Second polyline
|
||||
@returns {bool}
|
||||
*/
|
||||
startsAtExtremity: function (polyline, other) {
|
||||
if (!other) return false;
|
||||
var lla = polyline.getLatLngs(),
|
||||
llb = other.getLatLngs(),
|
||||
start = lla[0];
|
||||
return start.equals(llb[0]) || start.equals(llb[llb.length-1]);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns horizontal angle in degres between two points.
|
||||
@param {L.Point} a Coordinates of point A
|
||||
@param {L.Point} b Coordinates of point B
|
||||
@returns {Number} horizontal angle
|
||||
*/
|
||||
computeAngle: function(a, b) {
|
||||
return (Math.atan2(b.y - a.y, b.x - a.x) * 180 / Math.PI);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns slope (Ax+B) between two points.
|
||||
@param {L.Point} a Coordinates of point A
|
||||
@param {L.Point} b Coordinates of point B
|
||||
@returns {Object} with ``a`` and ``b`` properties.
|
||||
*/
|
||||
computeSlope: function(a, b) {
|
||||
var s = (b.y - a.y) / (b.x - a.x),
|
||||
o = a.y - (s * a.x);
|
||||
return {'a': s, 'b': o};
|
||||
},
|
||||
|
||||
/**
|
||||
Returns LatLng of rotated point around specified LatLng center.
|
||||
@param {L.LatLng} latlngPoint: point to rotate
|
||||
@param {double} angleDeg: angle to rotate in degrees
|
||||
@param {L.LatLng} latlngCenter: center of rotation
|
||||
@returns {L.LatLng} rotated point
|
||||
*/
|
||||
rotatePoint: function(map, latlngPoint, angleDeg, latlngCenter) {
|
||||
var maxzoom = map.getMaxZoom();
|
||||
if (maxzoom === Infinity)
|
||||
maxzoom = map.getZoom();
|
||||
var angleRad = angleDeg*Math.PI/180,
|
||||
pPoint = map.project(latlngPoint, maxzoom),
|
||||
pCenter = map.project(latlngCenter, maxzoom),
|
||||
x2 = Math.cos(angleRad)*(pPoint.x-pCenter.x) - Math.sin(angleRad)*(pPoint.y-pCenter.y) + pCenter.x,
|
||||
y2 = Math.sin(angleRad)*(pPoint.x-pCenter.x) + Math.cos(angleRad)*(pPoint.y-pCenter.y) + pCenter.y;
|
||||
return map.unproject(new L.Point(x2,y2), maxzoom);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the bearing in degrees clockwise from north (0 degrees)
|
||||
from the first L.LatLng to the second, at the first LatLng
|
||||
@param {L.LatLng} latlng1: origin point of the bearing
|
||||
@param {L.LatLng} latlng2: destination point of the bearing
|
||||
@returns {float} degrees clockwise from north.
|
||||
*/
|
||||
bearing: function(latlng1, latlng2) {
|
||||
var rad = Math.PI / 180,
|
||||
lat1 = latlng1.lat * rad,
|
||||
lat2 = latlng2.lat * rad,
|
||||
lon1 = latlng1.lng * rad,
|
||||
lon2 = latlng2.lng * rad,
|
||||
y = Math.sin(lon2 - lon1) * Math.cos(lat2),
|
||||
x = Math.cos(lat1) * Math.sin(lat2) -
|
||||
Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
|
||||
|
||||
var bearing = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360;
|
||||
return bearing >= 180 ? bearing-360 : bearing;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the point that is a distance and heading away from
|
||||
the given origin point.
|
||||
@param {L.LatLng} latlng: origin point
|
||||
@param {float} heading: heading in degrees, clockwise from 0 degrees north.
|
||||
@param {float} distance: distance in meters
|
||||
@returns {L.latLng} the destination point.
|
||||
Many thanks to Chris Veness at http://www.movable-type.co.uk/scripts/latlong.html
|
||||
for a great reference and examples.
|
||||
*/
|
||||
destination: function(latlng, heading, distance) {
|
||||
heading = (heading + 360) % 360;
|
||||
var rad = Math.PI / 180,
|
||||
radInv = 180 / Math.PI,
|
||||
R = 6378137, // approximation of Earth's radius
|
||||
lon1 = latlng.lng * rad,
|
||||
lat1 = latlng.lat * rad,
|
||||
rheading = heading * rad,
|
||||
sinLat1 = Math.sin(lat1),
|
||||
cosLat1 = Math.cos(lat1),
|
||||
cosDistR = Math.cos(distance / R),
|
||||
sinDistR = Math.sin(distance / R),
|
||||
lat2 = Math.asin(sinLat1 * cosDistR + cosLat1 *
|
||||
sinDistR * Math.cos(rheading)),
|
||||
lon2 = lon1 + Math.atan2(Math.sin(rheading) * sinDistR *
|
||||
cosLat1, cosDistR - sinLat1 * Math.sin(lat2));
|
||||
lon2 = lon2 * radInv;
|
||||
lon2 = lon2 > 180 ? lon2 - 360 : lon2 < -180 ? lon2 + 360 : lon2;
|
||||
return L.latLng([lat2 * radInv, lon2]);
|
||||
},
|
||||
|
||||
/**
|
||||
Returns the the angle of the given segment and the Equator in degrees,
|
||||
clockwise from 0 degrees north.
|
||||
@param {L.Map} map: Leaflet map to be used for this method
|
||||
@param {L.LatLng} latlngA: geographical point A of the segment
|
||||
@param {L.LatLng} latlngB: geographical point B of the segment
|
||||
@returns {Float} the angle in degrees.
|
||||
*/
|
||||
angle: function(map, latlngA, latlngB) {
|
||||
var pointA = map.latLngToContainerPoint(latlngA),
|
||||
pointB = map.latLngToContainerPoint(latlngB),
|
||||
angleDeg = Math.atan2(pointB.y - pointA.y, pointB.x - pointA.x) * 180 / Math.PI + 90;
|
||||
angleDeg += angleDeg < 0 ? 360 : 0;
|
||||
return angleDeg;
|
||||
},
|
||||
|
||||
/**
|
||||
Returns a point snaps on the segment and heading away from the given origin point a distance.
|
||||
@param {L.Map} map: Leaflet map to be used for this method
|
||||
@param {L.LatLng} latlngA: geographical point A of the segment
|
||||
@param {L.LatLng} latlngB: geographical point B of the segment
|
||||
@param {float} distance: distance in meters
|
||||
@returns {L.latLng} the destination point.
|
||||
*/
|
||||
destinationOnSegment: function(map, latlngA, latlngB, distance) {
|
||||
var angleDeg = L.GeometryUtil.angle(map, latlngA, latlngB),
|
||||
latlng = L.GeometryUtil.destination(latlngA, angleDeg, distance);
|
||||
return L.GeometryUtil.closestOnSegment(map, latlng, latlngA, latlngB);
|
||||
},
|
||||
});
|
||||
|
||||
return L.GeometryUtil;
|
||||
|
||||
}));
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Vendored
+3
File diff suppressed because one or more lines are too long
Vendored
+6
File diff suppressed because one or more lines are too long
@@ -0,0 +1,481 @@
|
||||
L.PhotonBase = L.Class.extend({
|
||||
|
||||
forEach: function (els, callback) {
|
||||
Array.prototype.forEach.call(els, callback);
|
||||
},
|
||||
|
||||
ajax: function (callback, thisobj) {
|
||||
if (typeof this.xhr === 'object') {
|
||||
this.xhr.abort();
|
||||
}
|
||||
this.xhr = new XMLHttpRequest();
|
||||
var self = this;
|
||||
this.xhr.open('GET', this.options.url + this.buildQueryString(this.getParams()), true);
|
||||
|
||||
this.xhr.onload = function(e) {
|
||||
self.fire('ajax:return');
|
||||
if (this.status === 200) {
|
||||
if (callback) {
|
||||
var raw = this.response;
|
||||
raw = JSON.parse(raw);
|
||||
callback.call(thisobj || this, raw);
|
||||
}
|
||||
}
|
||||
delete this.xhr;
|
||||
};
|
||||
|
||||
this.fire('ajax:send');
|
||||
this.xhr.send();
|
||||
},
|
||||
|
||||
buildQueryString: function (params) {
|
||||
var queryString = [];
|
||||
for (var key in params) {
|
||||
if (params[key]) {
|
||||
queryString.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
|
||||
}
|
||||
}
|
||||
return queryString.join('&');
|
||||
},
|
||||
|
||||
featureToPopupContent: function (feature) {
|
||||
var container = L.DomUtil.create('div', 'leaflet-photon-popup'),
|
||||
title = L.DomUtil.create('h3', '', container);
|
||||
title.innerHTML = feature.properties.label;
|
||||
return container;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
L.PhotonBaseSearch = L.PhotonBase.extend({
|
||||
|
||||
includes: ((typeof L.Evented !== 'undefined' && L.Evented.prototype) || L.Mixin.Events),
|
||||
|
||||
options: {
|
||||
url: 'https://photon.komoot.io/api/?',
|
||||
placeholder: 'Start typing...',
|
||||
minChar: 3,
|
||||
limit: 5,
|
||||
submitDelay: 300,
|
||||
includePosition: true,
|
||||
bbox: null,
|
||||
noResultLabel: 'No result',
|
||||
feedbackEmail: 'photon@komoot.de', // Set to null to remove feedback box
|
||||
feedbackLabel: 'Feedback'
|
||||
},
|
||||
|
||||
CACHE: '',
|
||||
RESULTS: [],
|
||||
KEYS: {
|
||||
LEFT: 37,
|
||||
UP: 38,
|
||||
RIGHT: 39,
|
||||
DOWN: 40,
|
||||
TAB: 9,
|
||||
RETURN: 13,
|
||||
ESC: 27,
|
||||
APPLE: 91,
|
||||
SHIFT: 16,
|
||||
ALT: 17,
|
||||
CTRL: 18
|
||||
},
|
||||
|
||||
initialize: function (input, options) {
|
||||
this.input = input;
|
||||
L.setOptions(this, options);
|
||||
var CURRENT = null;
|
||||
|
||||
try {
|
||||
Object.defineProperty(this, 'CURRENT', {
|
||||
get: function () {
|
||||
return CURRENT;
|
||||
},
|
||||
set: function (index) {
|
||||
if (typeof index === 'object') {
|
||||
index = this.resultToIndex(index);
|
||||
}
|
||||
CURRENT = index;
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
// Hello IE8
|
||||
}
|
||||
this.input.type = L.Browser.ie ? 'text' : 'search';
|
||||
this.input.placeholder = this.options.placeholder;
|
||||
this.input.autocomplete = 'off';
|
||||
this.input.autocorrect = 'off';
|
||||
L.DomEvent.disableClickPropagation(this.input);
|
||||
|
||||
L.DomEvent.on(this.input, 'keydown', this.onKeyDown, this);
|
||||
L.DomEvent.on(this.input, 'input', this.onInput, this);
|
||||
L.DomEvent.on(this.input, 'blur', this.onBlur, this);
|
||||
L.DomEvent.on(this.input, 'focus', this.onFocus, this);
|
||||
this.createResultsContainer();
|
||||
},
|
||||
|
||||
createResultsContainer: function () {
|
||||
this.resultsContainer = this.options.resultsContainer || L.DomUtil.create('ul', 'photon-autocomplete', document.querySelector('body'));
|
||||
},
|
||||
|
||||
resizeContainer: function()
|
||||
{
|
||||
var l = this.getLeft(this.input);
|
||||
var t = this.getTop(this.input) + this.input.offsetHeight;
|
||||
this.resultsContainer.style.left = l + 'px';
|
||||
this.resultsContainer.style.top = t + 'px';
|
||||
var width = this.options.width ? this.options.width : this.input.offsetWidth - 2;
|
||||
this.resultsContainer.style.width = width + 'px';
|
||||
},
|
||||
|
||||
onKeyDown: function (e) {
|
||||
switch (e.keyCode) {
|
||||
case this.KEYS.TAB:
|
||||
if(this.CURRENT !== null)
|
||||
{
|
||||
this.setChoice();
|
||||
}
|
||||
L.DomEvent.stop(e);
|
||||
break;
|
||||
case this.KEYS.RETURN:
|
||||
L.DomEvent.stop(e);
|
||||
this.setChoice();
|
||||
break;
|
||||
case this.KEYS.ESC:
|
||||
L.DomEvent.stop(e);
|
||||
this.hide();
|
||||
this.input.blur();
|
||||
break;
|
||||
case this.KEYS.DOWN:
|
||||
if(this.RESULTS.length > 0) {
|
||||
if(this.CURRENT !== null && this.CURRENT < this.RESULTS.length - 1) { // what if one resutl?
|
||||
this.CURRENT++;
|
||||
this.highlight();
|
||||
}
|
||||
else if(this.CURRENT === null) {
|
||||
this.CURRENT = 0;
|
||||
this.highlight();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case this.KEYS.UP:
|
||||
if(this.CURRENT !== null) {
|
||||
L.DomEvent.stop(e);
|
||||
}
|
||||
if(this.RESULTS.length > 0) {
|
||||
if(this.CURRENT > 0) {
|
||||
this.CURRENT--;
|
||||
this.highlight();
|
||||
}
|
||||
else if(this.CURRENT === 0) {
|
||||
this.CURRENT = null;
|
||||
this.highlight();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
},
|
||||
|
||||
onInput: function (e) {
|
||||
if (typeof this.submitDelay === 'number') {
|
||||
window.clearTimeout(this.submitDelay);
|
||||
delete this.submitDelay;
|
||||
}
|
||||
this.submitDelay = window.setTimeout(L.Util.bind(this.search, this), this.options.submitDelay);
|
||||
},
|
||||
|
||||
onBlur: function (e) {
|
||||
this.fire('blur');
|
||||
var self = this;
|
||||
setTimeout(function () {
|
||||
self.hide();
|
||||
}, 100);
|
||||
},
|
||||
|
||||
onFocus: function (e) {
|
||||
this.fire('focus');
|
||||
this.input.select();
|
||||
this.search(); // In case we have a value from a previous search.
|
||||
},
|
||||
|
||||
clear: function () {
|
||||
this.RESULTS = [];
|
||||
this.CURRENT = null;
|
||||
this.CACHE = '';
|
||||
this.resultsContainer.innerHTML = '';
|
||||
},
|
||||
|
||||
hide: function() {
|
||||
this.fire('hide');
|
||||
this.clear();
|
||||
this.resultsContainer.style.display = 'none';
|
||||
},
|
||||
|
||||
setChoice: function (choice) {
|
||||
choice = choice || this.RESULTS[this.CURRENT];
|
||||
if (choice) {
|
||||
this.hide();
|
||||
this.fire('selected', {choice: choice.feature});
|
||||
this.onSelected(choice.feature);
|
||||
this.input.value = '';
|
||||
}
|
||||
},
|
||||
|
||||
search: function() {
|
||||
var val = this.input.value;
|
||||
var minChar = typeof this.options.minChar === 'function' ? this.options.minChar(val) : val.length >= this.options.minChar;
|
||||
if (!val || !minChar) return this.clear();
|
||||
if(val + '' === this.CACHE + '') return;
|
||||
else this.CACHE = val;
|
||||
this._doSearch();
|
||||
},
|
||||
|
||||
_doSearch: function () {
|
||||
this.ajax(this.handleResults, this);
|
||||
},
|
||||
|
||||
_onSelected: function (feature) {
|
||||
},
|
||||
|
||||
onSelected: function (choice) {
|
||||
return (this.options.onSelected || this._onSelected).call(this, choice);
|
||||
},
|
||||
|
||||
_formatResult: function (feature, el) {
|
||||
var title = L.DomUtil.create('strong', '', el),
|
||||
detailsContainer = L.DomUtil.create('small', '', el),
|
||||
details = [],
|
||||
type = this.formatType(feature);
|
||||
if (feature.properties.name) {
|
||||
title.innerHTML = feature.properties.name;
|
||||
} else if (feature.properties.housenumber) {
|
||||
title.innerHTML = feature.properties.housenumber;
|
||||
if (feature.properties.street) {
|
||||
title.innerHTML += ' ' + feature.properties.street;
|
||||
}
|
||||
}
|
||||
if (type) details.push(type);
|
||||
if (feature.properties.city && feature.properties.city !== feature.properties.name) {
|
||||
details.push(feature.properties.city);
|
||||
}
|
||||
if (feature.properties.country) details.push(feature.properties.country);
|
||||
detailsContainer.innerHTML = details.join(', ');
|
||||
},
|
||||
|
||||
formatResult: function (feature, el) {
|
||||
return (this.options.formatResult || this._formatResult).call(this, feature, el);
|
||||
},
|
||||
|
||||
formatType: function (feature) {
|
||||
return (this.options.formatType || this._formatType).call(this, feature);
|
||||
},
|
||||
|
||||
_formatType: function (feature) {
|
||||
return feature.properties.osm_value === 'yes'
|
||||
? feature.properties.osm_key
|
||||
: feature.properties.osm_value;
|
||||
},
|
||||
|
||||
createResult: function (feature) {
|
||||
var el = L.DomUtil.create('li', '', this.resultsContainer);
|
||||
this.formatResult(feature, el);
|
||||
var result = {
|
||||
feature: feature,
|
||||
el: el
|
||||
};
|
||||
// Touch handling needed
|
||||
L.DomEvent.on(el, 'mouseover', function (e) {
|
||||
this.CURRENT = result;
|
||||
this.highlight();
|
||||
}, this);
|
||||
L.DomEvent.on(el, 'mousedown', function (e) {
|
||||
this.setChoice();
|
||||
}, this);
|
||||
return result;
|
||||
},
|
||||
|
||||
resultToIndex: function (result) {
|
||||
var out = null;
|
||||
this.forEach(this.RESULTS, function (item, index) {
|
||||
if (item === result) {
|
||||
out = index;
|
||||
return;
|
||||
}
|
||||
});
|
||||
return out;
|
||||
},
|
||||
|
||||
handleResults: function(geojson) {
|
||||
var self = this;
|
||||
this.clear();
|
||||
this.resultsContainer.style.display = 'block';
|
||||
this.resizeContainer();
|
||||
this.forEach(geojson.features, function (feature) {
|
||||
self.RESULTS.push(self.createResult(feature));
|
||||
});
|
||||
if (geojson.features.length === 0) {
|
||||
var noresult = L.DomUtil.create('li', 'photon-no-result', this.resultsContainer);
|
||||
noresult.innerHTML = this.options.noResultLabel;
|
||||
}
|
||||
if (this.options.feedbackEmail) {
|
||||
var feedback = L.DomUtil.create('a', 'photon-feedback', this.resultsContainer);
|
||||
feedback.href = 'mailto:' + this.options.feedbackEmail;
|
||||
feedback.innerHTML = this.options.feedbackLabel;
|
||||
}
|
||||
this.CURRENT = 0;
|
||||
this.highlight();
|
||||
if (this.options.resultsHandler) {
|
||||
this.options.resultsHandler(geojson);
|
||||
}
|
||||
},
|
||||
|
||||
highlight: function () {
|
||||
var self = this;
|
||||
this.forEach(this.RESULTS, function (item, index) {
|
||||
if (index === self.CURRENT) {
|
||||
L.DomUtil.addClass(item.el, 'on');
|
||||
}
|
||||
else {
|
||||
L.DomUtil.removeClass(item.el, 'on');
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
getLeft: function (el) {
|
||||
var tmp = el.offsetLeft;
|
||||
el = el.offsetParent;
|
||||
while(el) {
|
||||
tmp += el.offsetLeft;
|
||||
el = el.offsetParent;
|
||||
}
|
||||
return tmp;
|
||||
},
|
||||
|
||||
getTop: function (el) {
|
||||
var tmp = el.offsetTop;
|
||||
el = el.offsetParent;
|
||||
while(el) {
|
||||
tmp += el.offsetTop;
|
||||
el = el.offsetParent;
|
||||
}
|
||||
return tmp;
|
||||
},
|
||||
|
||||
getParams: function () {
|
||||
return {
|
||||
q: this.CACHE,
|
||||
lang: this.options.lang,
|
||||
limit: this.options.limit,
|
||||
osm_tag: this.options.osm_tag
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
L.PhotonSearch = L.PhotonBaseSearch.extend({
|
||||
|
||||
initialize: function (map, input, options) {
|
||||
this.map = map;
|
||||
L.PhotonBaseSearch.prototype.initialize.call(this, input, options);
|
||||
},
|
||||
|
||||
_onSelected: function (feature) {
|
||||
this.map.setView([feature.geometry.coordinates[1], feature.geometry.coordinates[0]], 16);
|
||||
},
|
||||
|
||||
getParams: function () {
|
||||
var params = L.PhotonBaseSearch.prototype.getParams.call(this);
|
||||
if (this.options.includePosition) {
|
||||
params.lat = this.map.getCenter().lat;
|
||||
params.lon = this.map.getCenter().lng;
|
||||
}
|
||||
if (this.options.bbox && this.options.bbox.length === 4) {
|
||||
params.bbox = this.options.bbox.join(',');
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
L.Control.Photon = L.Control.extend({
|
||||
|
||||
includes: ((typeof L.Evented !== 'undefined' && L.Evented.prototype) || L.Mixin.Events),
|
||||
|
||||
onAdd: function (map, options) {
|
||||
this.map = map;
|
||||
this.container = L.DomUtil.create('div', 'leaflet-photon');
|
||||
|
||||
this.options = L.Util.extend(this.options, options);
|
||||
|
||||
this.input = L.DomUtil.create('input', 'photon-input', this.container);
|
||||
this.search = new L.PhotonSearch(map, this.input, this.options);
|
||||
this.search.on('blur', this.forwardEvent, this);
|
||||
this.search.on('focus', this.forwardEvent, this);
|
||||
this.search.on('hide', this.forwardEvent, this);
|
||||
this.search.on('selected', this.forwardEvent, this);
|
||||
this.search.on('ajax:send', this.forwardEvent, this);
|
||||
this.search.on('ajax:return', this.forwardEvent, this);
|
||||
return this.container;
|
||||
},
|
||||
|
||||
// TODO onRemove
|
||||
|
||||
forwardEvent: function (e) {
|
||||
this.fire(e.type, e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
L.control.photon = function(options) {
|
||||
return new L.Control.Photon(options);
|
||||
}
|
||||
|
||||
L.Map.addInitHook(function () {
|
||||
if (this.options.photonControl) {
|
||||
this.photonControl = new L.Control.Photon(this.options.photonControlOptions || {});
|
||||
this.addControl(this.photonControl);
|
||||
}
|
||||
});
|
||||
|
||||
L.PhotonReverse = L.PhotonBase.extend({
|
||||
|
||||
includes: ((typeof L.Evented !== 'undefined' && L.Evented.prototype) || L.Mixin.Events),
|
||||
|
||||
options: {
|
||||
url: 'https://photon.komoot.de/reverse/?',
|
||||
limit: 1,
|
||||
handleResults: null
|
||||
},
|
||||
|
||||
initialize: function (options) {
|
||||
L.setOptions(this, options);
|
||||
},
|
||||
|
||||
doReverse: function (latlng) {
|
||||
latlng = L.latLng(latlng);
|
||||
this.fire('reverse', {latlng: latlng});
|
||||
this.latlng = latlng;
|
||||
this.ajax(this.handleResults, this);
|
||||
},
|
||||
|
||||
_handleResults: function (data) {
|
||||
/*eslint-disable no-console */
|
||||
console.log(data);
|
||||
/*eslint-enable no-alert */
|
||||
},
|
||||
|
||||
handleResults: function (data) {
|
||||
return (this.options.handleResults || this._handleResults).call(this, data);
|
||||
},
|
||||
|
||||
getParams: function () {
|
||||
return {
|
||||
lang: this.options.lang,
|
||||
limit: this.options.limit,
|
||||
lat: this.latlng.lat,
|
||||
lon: this.latlng.lng,
|
||||
osm_tag: this.options.osm_tag
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
/*! loglevel - v1.7.1 - https://github.com/pimterry/loglevel - (c) 2020 Tim Perry - licensed MIT */
|
||||
!function(a,b){"use strict";"function"==typeof define&&define.amd?define(b):"object"==typeof module&&module.exports?module.exports=b():a.log=b()}(this,function(){"use strict";function a(a,b){var c=a[b];if("function"==typeof c.bind)return c.bind(a);try{return Function.prototype.bind.call(c,a)}catch(b){return function(){return Function.prototype.apply.apply(c,[a,arguments])}}}function b(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(c){return"debug"===c&&(c="log"),typeof console!==i&&("trace"===c&&j?b:void 0!==console[c]?a(console,c):void 0!==console.log?a(console,"log"):h)}function d(a,b){for(var c=0;c<k.length;c++){var d=k[c];this[d]=c<a?h:this.methodFactory(d,a,b)}this.log=this.debug}function e(a,b,c){return function(){typeof console!==i&&(d.call(this,b,c),this[a].apply(this,arguments))}}function f(a,b,d){return c(a)||e.apply(this,arguments)}function g(a,b,c){function e(a){var b=(k[a]||"silent").toUpperCase();if(typeof window!==i&&l){try{return void(window.localStorage[l]=b)}catch(a){}try{window.document.cookie=encodeURIComponent(l)+"="+b+";"}catch(a){}}}function g(){var a;if(typeof window!==i&&l){try{a=window.localStorage[l]}catch(a){}if(typeof a===i)try{var b=window.document.cookie,c=b.indexOf(encodeURIComponent(l)+"=");-1!==c&&(a=/^([^;]+)/.exec(b.slice(c))[1])}catch(a){}return void 0===j.levels[a]&&(a=void 0),a}}var h,j=this,l="loglevel";"string"==typeof a?l+=":"+a:"symbol"==typeof a&&(l=void 0),j.name=a,j.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},j.methodFactory=c||f,j.getLevel=function(){return h},j.setLevel=function(b,c){if("string"==typeof b&&void 0!==j.levels[b.toUpperCase()]&&(b=j.levels[b.toUpperCase()]),!("number"==typeof b&&b>=0&&b<=j.levels.SILENT))throw"log.setLevel() called with invalid level: "+b;if(h=b,!1!==c&&e(b),d.call(j,b,a),typeof console===i&&b<j.levels.SILENT)return"No console available for logging"},j.setDefaultLevel=function(a){g()||j.setLevel(a,!1)},j.enableAll=function(a){j.setLevel(j.levels.TRACE,a)},j.disableAll=function(a){j.setLevel(j.levels.SILENT,a)};var m=g();null==m&&(m=null==b?"WARN":b),j.setLevel(m,!1)}var h=function(){},i="undefined",j=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),k=["trace","debug","info","warn","error"],l=new g,m={};l.getLogger=function(a){if("symbol"!=typeof a&&"string"!=typeof a||""===a)throw new TypeError("You must supply a name when creating a logger.");var b=m[a];return b||(b=m[a]=new g(a,l.getLevel(),l.methodFactory)),b};var n=typeof window!==i?window.log:void 0;return l.noConflict=function(){return typeof window!==i&&window.log===l&&(window.log=n),l},l.getLoggers=function(){return m},l.default=l,l});
|
||||
Vendored
+6
File diff suppressed because one or more lines are too long
Vendored
+7
File diff suppressed because one or more lines are too long
Vendored
+3
File diff suppressed because one or more lines are too long
+5662
File diff suppressed because it is too large
Load Diff
Vendored
+2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Vendored
+2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Vendored
+6
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user