Как добавить точку на полилинии где-то между двумя вершинами? - PullRequest
0 голосов
/ 28 мая 2019

Цель состоит в том, чтобы иметь редактируемую полилинию с настраиваемыми маркерами в каждой вершине.

Как я вижу, Map API V3 не позволяет этого. Поэтому я сделал редактируемую ломаную линию вот так:

let polyline = new self.google.maps.Polyline({
    strokeColor: '#000000',
    strokeOpacity: 0.3,
    strokeWeight: 3,
    editable: false,
    path: path,
    map: self.map
});

polyline.binder = new MVCArrayBinder(polyline.getPath());

let markers = [];
for (let i = 0; i < path.length; i++) {
    let marker = this.getBasicMarker(path[i]);
    marker.bindTo('position', polyline.binder, i.toString());
    markers.push(marker);
}
getBasicMarker(position){
    return new this.google.maps.Marker({
        position: position,
        map: this.map,
        icon: {
            url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
            size: new google.maps.Size(7, 7),
            anchor: new google.maps.Point(3.5, 3.5)
        },
        draggable: true,
        visible: false
    });
}
function MVCArrayBinder(mvcArray) {
    this.array_ = mvcArray;
}

MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
    if (!isNaN(parseInt(key))) {
        return this.array_.getAt(parseInt(key));
    } else {
        this.array_.get(key);
    }
};

MVCArrayBinder.prototype.set = function (key, val) {
    if (!isNaN(parseInt(key))) {
        this.array_.setAt(parseInt(key), val);
    } else {
        this.array_.set(key, val);
    }
};

Окончательная полилиния теперь выглядит так: http://sandbox.rubera.ru/img/2019-05-28_17-04-25.jpg. Я могу перетащить любую существующую точку. Обновление полилинии при перетаскивании точки.

Теперь мне нужно добавить новую вершину где-то между двумя существующими.

Вот где я застрял.

Может быть, есть другое решение, как решить задачу?

1 Ответ

0 голосов
/ 29 мая 2019

В случае, если кто-нибудь сталкивается с подобной задачей, вот несколько модификаций моего кода, размещенного выше.Это помогло мне окончательно решить проблему.

MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
    if (!isNaN(parseInt(key))) {
        return this.array_.getAt(parseInt(key));
    } else {
        this.array_.get(key);
    }
};

MVCArrayBinder.prototype.set = function (key, val) {
    if (!isNaN(parseInt(key))) {
        this.array_.setAt(parseInt(key), val);
    } else {
        this.array_.set(key, val);
    }
};

MVCArrayBinder.prototype.insertAt = function (key, val) {
    this.array_.insertAt(key, val);
};
google.maps.event.addListener(this.activePoly, 'click', function (e) {
    let path = $this.activePoly.getPath(),
        inserted = false;

    // find line segment
    for (let i = 0; i < path.getLength() - 1, !inserted; i++) {
        let tempPoly = new google.maps.Polyline({
            path: [path.getAt(i), path.getAt(i + 1)]
        });

        if (google.maps.geometry.poly.isLocationOnEdge(e.latLng, tempPoly, 10e-2)) {
            $this.activeRoute.binder.insertAt(i + 1, e.latLng);
            inserted = true;

            let marker = $this.getBasicMarker(e.latLng);
            marker.setVisible(true);

            // Add new marker to array
            $this.activeRoute.markers.splice(i + 1, 0, marker);

            // Have to rebind all markers
            $this.activeRoute.markers.forEach((marker, index) => {
                marker.bindTo('position', $this.activeRoute.binder, index.toString());
            });
        }
    }
});

Мой activeRoute - это объект со следующей структурой:

{polyline: polyline, markers: markers, binder: polyline.binder}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...