@PHPjedi

Где я упустил ошибку?

Где я упустил ошибку... Как исправить?
Это API Яндекс Карт.

Ошибка:

ymapnew.js:33 Uncaught ReferenceError: DeliveryCalculator is not defined
    at ymaps.ready (ymapnew.js:33)

ymaps.ready(() => {
    let map = new ymaps.Map('map', {
            center: [60.906882, 30.067233],
            zoom: 9,
            type: 'yandex#map',
            behaviors: ['scrollZoom', 'drag'],
            controls: []
        }),
        // Адрес начальной точки
        searchStartPoint = new ymaps.control.SearchControl({
            options: {
                useMapBounds: true,
                noPlacemark: true,
                noPopup: true,
                placeholderContent: 'Адрес начальной точки',
                size: 'large',
            },
        }),
        // Адрес конечной точки
        searchFinishPoint = new ymaps.control.SearchControl({
            options: {
                useMapBounds: true,
                noCentering: true,
                noPopup: true,
                noPlacemark: true,
                placeholderContent: 'Адрес конечной точки',
                size: 'large',
                float: 'none',
                position: {left: 10, top: 44},
            },
        }),

        calculator = new DeliveryCalculator(map, map.getCenter());

    map.controls.add(searchStartPoint);
    map.controls.add(searchFinishPoint);


    searchStartPoint.events.add('resultselect', (event) => {
        let result = searchStartPoint.getResultsArray(),
            selected = event.get('index'),
            point = result['selected'].geometry.getCoordinates();

        calculator.setStartPoint(point);
    }).add('load', (event) => {
        /*
         * По полю skip определяем, что это не дозагрузка данных.
         * По getRusultsCount определяем, что есть хотя бы 1 результат
         */

        if (!event.get('skip') && searchStartPoint.getResultsCount())
            searchStartPoint.showResult(0)
    });

    searchFinishPoint.events.add('resultselect', (event) => {
        let result = searchFinishPoint.getResultsArray(),
            selected = event.get('index'),
            point = result['selected'].geometry.getCoordinates();

        calculator.setFinishPoint(point);
    }).add('load', (event) => {
        /*
         * По полю skip определяем, что это не дозагрузка данных.
         * По getRusultsCount определяем, что есть хотя бы 1 результат
         */

        if (!event.get('skip') && searchFinishPoint.getResultsCount())
            searchFinishPoint.showResult(0)
    });



    // Пишем калькулятор
    DeliveryCalculator = (map, finish) => {
      this._map;
      this._start = null;
      this._route = null;

      map.events.add('click', this._onClick, this);
    };

    const ptp = DeliveryCalculator.prototype;


    ptp._onClick = (event) => {
        if (this._start)
            this.setFinishPoint(event.get('coords'));
        else
            this.setStartPoint(event.get('coords'));
    };

    ptp._onDragEnd = (event) => {
        this.getDirection();
    };

    ptp.getDirection = () => {
        if (this._route)
            this._map.geoObjects.remove(this._route);

        if (this._start && this._finish) {
            const self = this,
                start = this._start.geometry.getCoordinates(),
                finish = this._finish.geometry.getCoordinates();

            ymaps.geocode(start, {results:1}).then((geocode) => {
                let address = geocode.geoObjects.get(0) && geocode.geoObjects.get(0).properties.get('balloonContentBody') || '';

                ymaps.route([start, finish]).then((router) => {
                    let distance = Math.round(router.getLength() / 1000),
                        message = '<span>Distance: ' + distance + 'км.</span><br />' +
                            '<span style="font-weight: bold; font-style: italic">cost of delivery: %sр.</span>';


                    self._route = router.getPaths();
                    self._route.options.set( {strokeWidth: 5, strokeColor: '0000ffff', opacity: 0.5 });
                    self._map.getObjects.add(self._route);
                    self._start.properties.set('balloonContentBody', address + message.replace('%s', self.calculate(distance)));

                });
            });

            self._map.setBounds(self._map.geoObjects.getBounds())
        }
    };

    ptp.setStartPoint = (position) => {
        if (this._start)
            this._start.geometry.setCoordinates(position);
        else {
            this._start = new ymaps.Placemark(position, { iconContent: 'А' }, { draggable: true });
            this._start.events.add('dragend', this._onDragEnd, this);
            this._map.geoObjects.add(this._start);
        }

        if (this._finish)
            this.getDirection();
    };

    ptp.setFinishPoint = (position) => {
        if (this._finish)
            this._finish.geometry.setCoordinates(position);
        else {
            this._finish = new ymaps.Placemark(position, { iconContent: 'Б' }, { draggable: true });
            this._finish.events.add('dragend', this._onDragEnd, this);
            this._map.geoObjects.add(this._finish);
        }
        
        if (this._start)
            this.getDirection();
    };
    
    
    
    ptp.calculate = (len) => {
        const DELIVERY_TARIF = 20,
            MINIMUM_COST = 500;
        
        return Math.max(len * DELIVERY_TARIF, MINIMUM_COST);
    };








});
  • Вопрос задан
  • 325 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
Объявление DeliveryCalculator - перенесите его выше объявления переменной calculator, или замените function expression на function declaration.

UPD. У вас там в конструкторе вызывается метод, добавленный в прототип... Переносите выше всё, не только объявление функции, но и модификацию её прототипа.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы