当我使用 HERE API 3/3.1 移动可拖动标记时,如何重新计算路线?

How can I recalculate a route when I move a draggable marker using HERE API 3/3.1?

我正在使用 Here maps API 3/3.1 基于此文档开发网站 Route planning and navigation

当我单击地图并使用至少两个数组计算路线时,我添加了可拖动标记。

当我将标记移动到另一个位置时,它显示如下

最后,要创建新路线,我需要添加另一个标记

如您所见,之前的折线仍在地图上,而不是随着我的标记移动。我找到了这个 post () 但我不知道如何适应我的网站,因为它属于以前的版本。

希望你能帮帮我。

// Se declara un array para guardar los puntos en el mapa
    var arregloPuntos = [];
    var contGlobal = 0;


    // Crea las variables de inicio y final de la ruta
    let startMarker;
    let endMarker;

    let routeLine;

    // Variables para guardar info de los clics
    var clickLat, clickLon;


    // Initialize the platform object:
    var platform = new H.service.Platform({
        'apikey': 'API-KEY'
    });

    // Obtain the default map types from the platform object
    var maptypes = platform.createDefaultLayers();

    // Instantiate (and display) a map object:
    var map = new H.Map(
        document.getElementById('mapContainer'),
        maptypes.vector.normal.map,
        {
            zoom: 15,
            center: { lng: -101.68, lat: 21.1236 }
        });

    // Enable the event system on the map instance:
    var mapEvents = new H.mapevents.MapEvents(map);

    // Add event listener:
    map.addEventListener('tap', function (evt) {
        // Log 'tap' and 'mouse' events:
        console.log(evt.type, evt.currentPointer.type);
    });

    // Instantiate the default behavior, providing the mapEvents object:
    var behavior = new H.mapevents.Behavior(mapEvents);


    // Add the click event listener.
    addDraggableMarker(map, behavior);

    // Funcion para agregar marker arrastrable
    function addDraggableMarker(map, behavior) {

        // Evento que crea el marker haciendo clic en el mapa
        map.addEventListener("tap", event => {
            var position = map.screenToGeo(
                event.currentPointer.viewportX,
                event.currentPointer.viewportY);
            // Imprime posicion
            //console.log(position);

            // Agrega las coordenadas del tap en el arreglo
            arregloPuntos.push(position);
            for (var contGlobal in arregloPuntos) {
                contGlobal++;
            }
            console.log(contGlobal);
            console.log(arregloPuntos);

            for (let j = 0; j < arregloPuntos.length; j++) {
                //Crea el marker a partir de la constante position dando lat y lon
                var marker = new H.map.Marker({ lat: arregloPuntos[j].lat, lng: arregloPuntos[j].lng }, {
                    // mark the object as volatile for the smooth dragging
                    volatility: true
                });
            }
            // Ensure that the marker can receive drag events
            marker.draggable = true;
            map.addObject(marker);

            // disable the default draggability of the underlying map
            // and calculate the offset between mouse and target's position
            // when starting to drag a marker object:
            map.addEventListener('dragstart', function (ev) {
                var target = ev.target,
                    pointer = ev.currentPointer;
                if (target instanceof H.map.Marker) {
                    var targetPosition = map.geoToScreen(target.getGeometry());
                    target['offset'] = new H.math.Point(pointer.viewportX - targetPosition.x, pointer.viewportY - targetPosition.y);
                    behavior.disable();
                }
                // Se droppea el contenido, para que pueda tomar los nuevos valores
                arregloPuntos.splice(position);         

            }, false);

            // re-enable the default draggability of the underlying map
            // when dragging has completed
            map.addEventListener('dragend', function (ev) {
                var target = ev.target;
                if (target instanceof H.map.Marker) {
                    behavior.enable();
                }

                // Se sobre escribe la posicion del marker
                position = map.screenToGeo(
                    event.currentPointer.viewportX,
                    event.currentPointer.viewportY);

                //arregloPuntos.splice(position);
                arregloPuntos.push(marker.getGeometry());
                console.log(contGlobal);
                console.log(arregloPuntos);      

                // Metodos de prueba para verificar el cambio en posición
                // marker.getGeometry obtiene los valores de lat y lon del marcador, incluso si este se mueve
                // Defecto: Cada vez que se arrastra el mapa despues de que se agrega un marcador, la consola
                // imprimira las coordenadas cuando se atrastre el mapa, ya que el API las detecta como la
                // funcion drag
                console.log(marker.getGeometry());
            }, false);

            // Listen to the drag event and move the position of the marker
            // as necessary
            map.addEventListener('drag', function (ev) {
                var target = ev.target,
                    pointer = ev.currentPointer;
                if (target instanceof H.map.Marker) {
                    target.setGeometry(map.screenToGeo(pointer.viewportX - target['offset'].x, pointer.viewportY - target['offset'].y));
                }
            }, false);             

            for (let i = 0; i < arregloPuntos.length; i++) {

                var routingParameters = {
                    'routingMode': 'fast',
                    'transportMode': 'car',
                    // The start point of the route:
                    'origin': '',
                    // The end point of the route:
                    'destination': '',
                    // Include the route shape in the response
                    'return': 'polyline'
                };

                if (i < arregloPuntos.length - 1 && arregloPuntos.length > 0) {

                    routingParameters.origin = arregloPuntos[i].lat + ',' + arregloPuntos[i].lng;
                    startMarker = routingParameters.origin;

                    routingParameters.destination = arregloPuntos[i + 1].lat + ',' + arregloPuntos[i + 1].lng;
                    endMarker = routingParameters.destination;


                    // Define a callback function to process the routing response:
                    var onResult = function (result) {
                        // ensure that at least one route was found
                        if (result.routes.length) {
                            result.routes[0].sections.forEach((section) => {
                                // Create a linestring to use as a point source for the route line
                                let linestring = H.geo.LineString.fromFlexiblePolyline(section.polyline);

                                // Create a polyline to display the route:
                                routeLine = new H.map.Polyline(linestring, {
                                    style: { strokeColor: 'black', lineWidth: 3 }
                                });

                                // Add the route polyline and the two markers to the map:
                                map.addObjects([routeLine, startMarker, endMarker]);

                                // Set the map's viewport to make the whole route visible:
                                map.getViewModel().setLookAtData({ bounds: routeLine.getBoundingBox() });

                            });
                        }
                    };

                } else {
                    // No tener puesto alguno de estos da un error de Bad request
                    routingParameters.origin = arregloPuntos[i].lat + ',' + arregloPuntos[i].lng;

                    routingParameters.destination = arregloPuntos[i].lat + ',' + arregloPuntos[i].lng;
                }

                // Get an instance of the routing service version 8:
                var router = platform.getRoutingService(null, 8);

                // Call calculateRoute() with the routing parameters,
                // the callback and an error callback function (called if a
                // communication error occurs):
                router.calculateRoute(routingParameters, onResult,
                    function (error) {
                        alert(error.message);
                    });

                //console.log(arregloPuntos[0].lat);
            }

        });

    }

在这里你可以找到例子:

Routing with Directions - 演示了如何使用自定义方向渲染器组件在页面上显示机动指令。

https://github.com/heremaps/examples

根据您提到的标记拖动示例,您必须在 dragend 回调中调用路由 API。要清除之前的路线,当您从折线绘制路线时,请先将折线添加到组中。然后使用 groupName.removeAll();

请参考https://developer.here.com/documentation/examples/maps-js/resizable-geoshapes/resizable-polyline。您可以在 Polyline 对象中添加多个中间点。每次如果有多个目的地,则可以更改折线对象。