Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ymaps.modules.define('AnimatedLine', [
- 'util.defineClass',
- 'Polyline',
- 'vow'
- ], function(provide, defineClass, Polyline, vow) {
- /**
- * @fileOverview Анимированная линия.
- */
- /**
- * Создает экземпляр анимированной линии.
- * @class AnimatedLine. Представляет собой геообъект с геометрией geometry.LineString.
- * @param {Boolean} [options.animationTime = 4000] Длительность анимации.
- **/
- function AnimatedLine(geometry, properties, options) {
- AnimatedLine.superclass.constructor.call(this, geometry, properties, options);
- this._loopTime = 50;
- this._animationTime = this.options.get('animationTime', 300);
- // Вычислим длину переданной линии.
- var distance = 0;
- var previousElem = geometry[0];
- this.geometry.getCoordinates().forEach(function(elem) {
- distance += getDistance(elem, previousElem);
- // console.log(distance)
- previousElem = elem;
- });
- // Вычислим минимальный интервал отрисовки.
- this._animationInterval = distance / this._animationTime * this._loopTime;
- // Создадим массив с более частым расположением промежуточных точек.
- this._smoothCoords = generateSmoothCoords(geometry, this._animationInterval);
- // console.log(generateSmoothCoords(geometry, this._animationInterval))
- }
- defineClass(AnimatedLine, Polyline, {
- // Анимировать линию.
- start: function() {
- var value = 0;
- var coords = this._smoothCoords;
- var line = this;
- var loopTime = this._loopTime;
- // Будем добавлять по одной точке каждые 50 мс.
- function loop(value, currentTime, previousTime) {
- if (value < coords.length) {
- if (!currentTime || (currentTime - previousTime) > loopTime) {
- line.geometry.set(value, coords[value]);
- value++;
- previousTime = currentTime;
- }
- requestAnimationFrame(function(time) {
- loop(value, time, previousTime || time)
- });
- } else {
- // Бросаем событие окончания отрисовки линии.
- line.events.fire('animationfinished');
- }
- }
- loop(value);
- },
- // Убрать отрисованную линию.
- reset: function() {
- this.geometry.setCoordinates([]);
- },
- // Запустить полный цикл анимации.
- animate: function() {
- this.reset();
- this.start();
- var deferred = vow.defer();
- this.events.once('animationfinished', function() {
- deferred.resolve();
- });
- return deferred.promise();
- }
- });
- // Функция генерации частых координат по заданной линии.
- function generateSmoothCoords(coords, interval) {
- var smoothCoords = [];
- smoothCoords.push(coords[0]);
- for (var i = 1; i < coords.length; i++) {
- var difference = [coords[i][0] - coords[i - 1][0], coords[i][1] - coords[i - 1][1]];
- var maxAmount = Math.max(Math.abs(difference[0] / interval), Math.abs(difference[1] / interval));
- var minDifference = [difference[0] / maxAmount, difference[1] / maxAmount];
- var lastCoord = coords[i - 1];
- while (maxAmount > 1) {
- lastCoord = [lastCoord[0] + minDifference[0], lastCoord[1] + minDifference[1]];
- smoothCoords.push(lastCoord);
- maxAmount--;
- }
- smoothCoords.push(coords[i])
- }
- return smoothCoords;
- }
- // Функция нахождения расстояния между двумя точками на плоскости.
- function getDistance(point1, point2) {
- return Math.sqrt(
- Math.pow((point2[0] - point1[0]), 2) +
- Math.pow((point2[1] - point1[1]), 2)
- );
- }
- provide(AnimatedLine);
- });
- var firstAnimatedLine = new ymaps.AnimatedLine([
- [55.761223661714205, 37.57854299428123],
- [55.76129474190374, 37.57836060406823],
- [55.76149285834102, 37.57855640532632],
- [55.76173267134118, 37.57864573959325],
- [55.761782872763874, 37.578559582240004],
- [55.7622647306412, 37.57857741008619],
- [55.76247342821094, 37.57840038429122],
- [55.762818964832924, 37.57765342764373],
- [55.76292179998886, 37.57748713068481],
- [55.762890042102114, 37.577167947812036],
- [55.76292179998886, 37.576878269238435],
- [55.763076052212064, 37.57669587902541],
- [55.76309672830313, 37.57723949881904]
- ], {}, {
- // Задаем цвет.
- strokeColor: "#ED4543",
- // Задаем ширину линии.
- strokeWidth: 5,
- // Задаем длительность анимации.
- animationTime: 10000
- });
- // Добавляем линии на карту.
- myMap.geoObjects.add(firstAnimatedLine);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement