Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Here JavaScript API 3.0 - How to implement a draggable marker

I would like to implement a draggable marker with the recently released JavaScript API 3.0.

Using the old API it was quite easy. After setting the draggable attribute to true you were able to move the marker on the map around.

The migration guide for the new API 3.0 located [here][1] states that after enabling events on map objects and setting the 'draggable' property to 'true' the corresponding events have to be implemented.

marker.addEventListener('dragstart', function() {
//handle drag start here
});
marker.addEventListener('drag', function() {
//handle drag here
});
marker.addEventListener('dragend', function() {
//handle drag end here
});

I'm not sure how to implement this dragging functionality in the corresponding events though. For sure the new location has to be calculated, but what would it look like so that the marker is moved according to the mouse position? The following code snippet needs to be extended somehow ...

marker.addEventListener('drag', function(evt) {
  var coord = map.screenToGeo(evt.currentPointer.viewportX,
            evt.currentPointer.viewportY);
  evt.target.setPosition( coord );
});

Thanks for your help, Seppal

evt [1]: http://developer.here.com/documentation/download/maps_js_html5_nlp/3.0.5/Maps%20API%20for%20JavaScript%20v3.0.5%20Migration%20Guide.pdf "here"

like image 612
hurrassinger Avatar asked Jan 09 '23 17:01

hurrassinger


1 Answers

A working example of creating draggable markers in the HERE Maps API for JavaScript 3.0 can be found in the Find the nearest marker example. There are three parts to setting it up.

  • Firstly set marker.draggable = true so it can receive drag events

    marker = new H.map.Marker(...);
    marker.draggable = true;
    map.addObject(marker);
    
  • Secondly disable the default draggability of the underlying map (i.e. the instance of H.mapevents.Behavior) when starting to drag a marker object:

    map.addEventListener('dragstart', function(ev) {
      var target = ev.target;
      if (target instanceof H.map.Marker) {
        behavior.disable();
      }
    }, false);
    
    
    map.addEventListener('dragend', function(ev) {
      var target = ev.target;
      if (target instanceof mapsjs.map.Marker) {
        behavior.enable();
      }
    }, false);
    
  • Thirdly listener to the drag event, and update the marker using setPosition()

    map.addEventListener('drag', function(ev) {
      var target = ev.target,
          pointer = ev.currentPointer;
      if (target instanceof mapsjs.map.Marker) {
        target.setPosition(map.screenToGeo(pointer.viewportX, pointer.viewportY));
      }
    }, false);
    
like image 128
Jason Fox Avatar answered Jan 12 '23 07:01

Jason Fox