Michael
Michael

Reputation: 51

Drag leaflet marker outside map

I am using leaflet markers in my ASP.NET MVC 5 application.

I need to drag marker outside application to a div element, where I want to get its id to perform further operations.

    marker=new  L.marker([latNumber,longNumber], {draggable:'true'});
    marker.id = "ABC";
    $('#'+ marker.id).draggable();  // draggable jquery UI
    marker.on('dragend', function(event){


    var marker = event.target;
    var position = marker.getLatLng();
    console.log(position);
    marker.setLatLng(position,{draggable:'true'}).bindPopup(position).update();
});

On the other hand I am using droppable element of jquery UI

  $("#navs").droppable({
        drop: function (event, ui) {
            alert('dropped')
        }
    });

I do not get dropped event on navs element when I drop it over it. What changes I need to do to make it work.

If someone can further explain this, it would be of great help too.

Upvotes: 1

Views: 2160

Answers (2)

Voider
Voider

Reputation: 11

Actually, there seems to be a workaround. Leaflet markers calls an event "add" after the marker is added to the map, and becomes visible. In that event you can initialize a draggable on the icon corresponding to that marker.

m=L.marker([lat,lng],{
   title:title,
   draggable:true
  });
 m.on("add",function(){
    $(this._icon).data("marker",this);
    $(this._icon).draggable({
      appendTo:"body",
      helper:"clone",
      zIndex:1000
    });
 });

"appendTo" is required for dragging outside of leaflet panel. zIndex should be higher than leaflet map zIndex (not sure if it's fixed, it's 600 on my page). Probably, you will need a helper function for copying an icon, I've customized my helper (marker is accessible via data "marker").

I've used that with leaflet 1.0.3.

Upvotes: 1

YaFred
YaFred

Reputation: 10008

You can't drag a Leaflet marker outside the map.

The draggable option of a marker and the draggable concept of jQuery are completely different.

That beeing said, you can pretend a marker is dragged by using the image of the marker an place it above the map: it is not part of the map, but it looks like (that is what the link you mention is referring to)

<div>
<div id='map'></div>
<img style="position: absolute; left: 300px; top: 200px; z-index: 1000" id="fakeMarker" src="https://unpkg.com/[email protected]/dist/images/marker-icon.png"></img>
</div>

<ul id="liste">
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
</ul>

<div id="log"></div>

<script>
$( function() {
   $("#fakeMarker").draggable();

   $( "#liste li" ).droppable({
     accept: "#fakeMarker",
     drop: function( event, ui ) {
         $( "#log" ).html("dropped on " + $(this).html());  
     }
   });
 } );
 </script>  

Here is an example: https://yafred.github.io/leaflet-tests/20161120-drag-and-drop-outside-map/

Upvotes: 0

Related Questions