Here Maps API: Detecting when a Marker is dragged and dropped onto a Polyline

给你一囗甜甜゛ 提交于 2021-01-29 18:33:21

问题


I have draggable markers on a Here Map, and I'd like to detect when a marker is dragged and dropped onto a Polyline. I haven't been able to find a good way to detect that the marker is dropped on or near the polyline. It would be nice if I could add an "dragend" event listener to the Polyline object, but that doesn't seem to be supported on objects other than the actual map.

Another approach would be to determine the distance to the Polyline from the point that the dragend occurs, but I haven't found a straightforward way to calculate that distance. (Though I've found the example for finding the nearest marker to a point.)

Any suggestions?


回答1:


It is possible to add dragend event listener on map objects.

This code should work for you (in 3.0 API version):

var lineString = new H.geo.LineString([0, 0, 0, 50, 50, 0]),
    polyline = new H.map.Polyline(lineString, {style: {lineWidth: 15, strokeColor: 'red'}}),
    marker = new H.map.Marker({lat: 30, lng: 0});

  // Ensure that the marker can receive drag events
  marker.draggable = true;

  // add objects to the map
  map.addObjects([polyline, marker]);

  // set map center and zoom
  map.setCenter({lat: 30, lng: 0});
  map.setZoom(3);

  // disable map's behavior and calculate the offset between mouse and target's position
  // when starting to drag a marker object:
  marker.addEventListener('dragstart', function(ev) {
    var target = ev.target,
        pointer = ev.currentPointer,
        targetPosition = map.geoToScreen(target.getGeometry());

    target['offset'] = new H.math.Point(pointer.viewportX - targetPosition.x, pointer.viewportY - targetPosition.y);
    behavior.disable();
  }, false);

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

  // re-enable behavior and check if marker was dropped on polyline
  marker.addEventListener('dragend', function(ev) {
    behavior.enable();
    var pointer = ev.currentPointer,
        objects = map.getObjectsAt(pointer.viewportX, pointer.viewportY),
        droppedOnPolyline = false;
    objects.forEach(function(object) {
      if (object === polyline) {
        droppedOnPolyline = true;
      }
    });

    console.log('marker dropped on polyline? %s', droppedOnPolyline);
  }, false);



来源:https://stackoverflow.com/questions/58458099/here-maps-api-detecting-when-a-marker-is-dragged-and-dropped-onto-a-polyline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!